| 函数 | 功能 |
|---|---|
| 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
本文介绍了C++头文件algorithm中关于min和max的使用,包括min、max、minmax函数以及min_element和max_element迭代器。通过示例代码展示了如何找到序列中的最小值、最大值及其组合,并解释了其返回结果和适用场景。

2万+

被折叠的 条评论
为什么被折叠?



