The use of *max_element and *min_element in C++ to obtain the maximum and minimum values in arrays and vectors

The function return value of max_element() is a pointer, which corresponds to the position corresponding to the maximum value, and *max_element corresponds to the specific value of the maximum value, which is more efficient than setting the temporary variable for loop traversal to solve the maximum (small) value.
The test case is as follows:

#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;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34612223/article/details/113916563