函数 | 功能 |
---|---|
min | 返回最小元素 |
max | 返回最大元素 |
minmax | 返回最小和最大元素 |
nin_element | 返回一定范围内的最小元素 |
max_element | 返回一定范围内的最大元素 |
minmax_element | 返回一定范围内的最小和最大元素 |
example
#include
#include
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;
}
example
#include
#include
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;
}
结果返回一对值:a和b。第一元素是最小值,第二个元素是最大值。
example
#include
#include
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;
}
ForwardIterator min_element (ForwardIterator first, ForwardIterator last, Compare comp);
结果返回一个迭代器,它指向某个范围内最小或最大元素;如果这个范围为空,则返回comp。
example
#include
#include
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)<cout << "The largest element is " << *max_element(myints, myints + 6)<//using function as comp
cout << "The smallest element is" << *min_element(myints, myints + 6,myfunction)<cout << "The largest element is " << *max_element(myints, myints + 6,myfunction)<//using object as comp
cout << "The smallest element is" << *min_element(myints, myints + 6,myobject)<cout << "The largest element is " << *max_element(myints, myints + 6,myobject)<return 0;
}
example
#include
#include
#include
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;
}