如何使用C++中的STL找到向量的最大元素?
给定一个向量,在C++中使用STL找到此向量的最大元素。 例如:
输入: {1, 45, 54, 71, 76, 12}
输出: 76
输入: {1, 7, 5, 4, 6, 12}
输出: 12
方法: 可以使用STL中提供的*max_element()函数找到最大元素。
语法:
*max_element(first_index, last_index);
// C++程序,使用*max_element()在STL中找到数组的最大值
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 获取向量
vector<int> a = { 1, 45, 54, 71, 76, 12 };
// 打印向量
cout << "Vector: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << endl;
// 查找最大元素
cout << "\n最大元素 = "
<< *max_element(a.begin(), a.end());
return 0;
}
输出:
Vector: 1 45 54 71 76 12
最大元素 = 76
时间复杂度: O(N),其中N是向量给定范围内的元素数。
辅助空间: O(1)