Use of min_element() and max_element() functions

min_element() and max_element
header files: #include
function: returns the minimum and maximum values ​​in the container.
max_element(first,end,cmp); where cmp is an optional parameter!
max function | C++ returns the maximum value in the array - max_element function

In the header file #include, the iterator is returned, so add * in front of the output value

  1. The third parameter cmp can be writable or not, max_element() and min_element() are arranged from small to large by default, then max_element() outputs the last value, min_element() outputs the first value, but if the custom cmp function writes is arranged from large to small, then the two results of max_element() and min_element() will be reversed

  2. It can be used for vector or vector, etc., it can also be used for int arr[4] or string arr[4], it can also be used for structure vector or structure array~

#include<bits/stdc++.h>
using namespace std; 
struct node {
   int x, y;
};
bool cmp1(node a, node b) {
    return a.x > b.x;
}
int main() {
    vector<int> v(3);
    int arr[4];
    vector<node> v1(3);
    cout << *max_element(v.begin(), v.end());
    cout << *min_element(arr, arr + 4);
    cout << (*max_element(v1.begin(), v1.end(), cmp1)).y;
    return 0;
}
#include<iostream>  
#include<algorithm>  
using namespace std;  
bool cmp(int a,int b){  
      return a < b;  
}  
int main(){  
      int num[]={2,3,1,6,4,5};  
      cout << "最小值是 " << *min_element(num,num+6) << endl;  
      cout << "最大值是 " << *max_element(num,num+6) << endl;  
      cout << "最小值是 " << *min_element(num,num+6,cmp) << endl;  
      cout << "最大值是 " << *max_element(num,num+6,cmp) << endl;  
      return 0;   
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325736742&siteId=291194637