C++头文件algorithm 3——Min/Max

来源:互联网 发布:华沙 知乎 编辑:程序博客网 时间:2024/06/05 23:03
函数 功能 min 返回最小元素 max 返回最大元素 minmax 返回最小和最大元素 nin_element 返回一定范围内的最小元素 max_element 返回一定范围内的最大元素 minmax_element 返回一定范围内的最小和最大元素

min

example

#include<iostream>#include<algorithm>using namespace std;int main(){    cout << "min(4,5)=" << min(4, 5) << endl;    cout << "min('a','n')=" << min('a', 'n') << endl;    cout << "min(5.6,3.12)=" << min(5.6, 3.12) << endl;    return 0;}

output
这里写图片描述

max

example

#include<iostream>#include<algorithm>using namespace std;int main(){    cout << "max(4,5)=" << max(4, 5) << endl;    cout << "max('a','n')=" << max('a', 'n') << endl;    cout << "max(5.6,3.12)=" << max(5.6, 3.12) << endl;    return 0;}

output
这里写图片描述

minmax

结果返回一对值:a和b。第一元素是最小值,第二个元素是最大值。

example

#include<iostream>#include<algorithm>using namespace std;int main(){    auto res = minmax({ 1, 2, 3, 4, 5, 6, 7, 8, 9 });    cout << "minmax({ 1, 2, 3, 4, 5, 6, 7, 8, 9 })\t";    cout << "min:" << res.first << "\tmax:" << res.second << endl;    auto res2 = minmax({ 1,1,1,1,1,1,1,1,1});    cout << "minmax({ 1,1,1,1,1,1,1,1,1 })\t";    cout << "min:" << res2.first << "\tmax:" << res2.second << endl;    return 0;}

output
这里写图片描述

min_element&max_element

ForwardIterator min_element (ForwardIterator first, ForwardIterator last, Compare comp);
结果返回一个迭代器,它指向某个范围内最小或最大元素;如果这个范围为空,则返回comp。

example

#include<iostream>#include<algorithm>using namespace std;bool myfunction(int i, int j){ return (i < j); }struct myclass{    bool operator()(int i, int j){ return i < j; }}myobject;int main(){    int myints[] = {4,7,8,2,9,5};    //using default comparison    cout << "The smallest element is" << *min_element(myints, myints + 6)<<endl;    cout << "The largest element is  " << *max_element(myints, myints + 6)<<endl;    //using function as comp    cout << "The smallest element is" << *min_element(myints, myints + 6,myfunction)<<endl;    cout << "The largest element is  " << *max_element(myints, myints + 6,myfunction)<<endl;    //using object as comp    cout << "The smallest element is" << *min_element(myints, myints + 6,myobject)<<endl;    cout << "The largest element is  " << *max_element(myints, myints + 6,myobject)<<endl;    return 0;}

output
这里写图片描述

minmax_element

example

#include<iostream>#include<algorithm>#include<vector>using namespace std;int main(){    vector<int> myvector= { 4, 7, 8, 2, 9, 5 };    auto res = minmax_element(myvector.begin(), myvector.end());    cout << "all element :";    for (auto x : myvector)        cout << x << " ";    cout << "\nmin:\t" << *res.first <<" at position: "<<(res.first-myvector.begin())<< endl;    cout << "max\t" << *res.second << " at position: " << (res.second-myvector.begin())<< endl;    return 0;}

output
这里写图片描述

原创粉丝点击