C++中使用max_element函数可快速查找数组或容器中的最大值,该函数定义在头文件中,返回指向最大元素的迭代器,需通过解引用获取实际值;对于普通数组,传入起始和结束地址,如max_element(arr, arr + n);对于vector等STL容器,使用begin()和end()作为参数,如max_element(vec.begin(), vec.end());示例代码展示了对int数组{3,7,2,9,1,5}求最大值得到9,以及对vector{10,45,23,67,12}求最大值得到67,用法一致且简便。

在C++中,查找数组中的最大值可以通过标准库中的 max_element 函数快速实现。这个函数定义在
max_element 函数基本用法
max_element 的常用形式如下:
max_element(起始迭代器, 结束迭代器)- 返回值是一个迭代器,指向最大元素的位置。
- 若要获取最大值本身,需使用解引用操作符
*。
示例:查找普通数组中的最大值
以下代码演示如何使用 max_element 查找整型数组中的最大值:
#include iostream>#include
using namespace std;
int main() {
int arr[] = {3, 7, 2, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// 使用 max_element 查找最大值
int maxValue = *max_element(arr, arr + n);
cout return 0;
}
输出结果为:
数组中的最大值是: 9
结合 vector 使用 max_element
对于 vector 等STL容器,用法类似:
立即学习“C++免费学习笔记(深入)”;
#include#include
#include
using namespace std;
int main() {
vector
int maxValue = *max_element(vec.begin(), vec.end());
cout return 0;
}
输出:
vector 中的最大值是: 67
基本上就这些。只要包含










