C++中*max_element和*min_element在数组、vector中获取最大最小值的用法

max_element( ) 的函数返回值是个指针,对应的是最大值所对应的位置,*max_element则对应最大值的具体数值,比设置临时变量for循环遍历求解最大(小)值要高效。
测试用例如下所示:

#include <vector>
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
    
    
    int a[] = {
    
    -5,-3,-3,-2,7,1}, b[] ={
    
    -10,-5,3,4,6};
    cout << *max_element(a, a + sizeof(a)/sizeof(int)) << endl;
    cout << *min_element(b, b + sizeof(b)/sizeof(int)) << endl;
    vector<int> c{
    
    -5,-3,-3,-2,7,1}, d{
    
    -10,-5,3,4,6};
    cout << *max_element(c.begin(), c.end()) << endl;
    cout << *min_element(d.begin(), d.end()) << endl;
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34612223/article/details/113916563