STLalgorithm算法minmax,minmax_element(36)
minmax原型:
std::minmax
- C++11
- C++14
default (1)
template
pair <const T&,const T&> minmax (const T& a, const T& b);
custom (2)
template <class T, class Compare>
pair <const T&,const T&> minmax (const T& a, const T& b, Compare comp);
initializer list (3)
template
pair<T,T> minmax (initializer_list
template <class T, class Compare>
pair<T,T> minmax (initializer_list
该函数返回一个pair,该pair的first元素的值为a,b中的最小值,second元素的值为a.b中的最大值。
使用operator<进行比较。
如果a=b,那么将返回make_pair(a,b).
对于(3),返回初始化列表中的最小最大值的pair,如果最值多于一个,firstf返回的是第一个出现的最小值,second返回的是最后一个出现的最大值。
其行为类似于:
template
return (b<a) ? std::make_pair(b,a) : std::make_pair(a,b);
}
一个简单的例子:
#include
#include
#include
using namespace std;
void minmax2(){
auto it=minmax(20,10);
cout<<” auto it=minmax(20,10)”<<endl;
cout<<”it.first()=”<<it.first<<” ,it.second=”<<it.second<<endl;
auto it2=minmax({2,3,5,7,1,3,1});
cout<<”auto it2=minmax({2,3,5,7,1,3,1})”<<endl;
cout<<”it2.first()=”<<it2.first<<” ,it2.second=”<<it2.second<<endl;
}
运行截图:
minmax_element原型:
std::minmax_element
default (1)
template
pair<ForwardIterator,ForwardIterator>
minmax_element (ForwardIterator first, ForwardIterator last);
custom (2)
template <class ForwardIterator, class Compare>
pair<ForwardIterator,ForwardIterator>
minmax_element (ForwardIterator first, ForwardIterator last, Compare comp);
该函数是返回指定范围内的最大最小值的元素的迭代器组成的一个pair,如果最值多于一个,firstf返回的是第一个出现的最小值的迭代器,second返回的是最后一个出现的最大值的迭代器。
使用operator<进行比较。
一个简单的例子:
#include
#include
#include
using namespace std;
void minmaxelement(){
vector
cout<<”vi=”;
for(int i:vi)
cout<<i<<” “;
cout<<endl;
auto it=minmax_element(vi.begin(),vi.end());
cout<<” auto it=minmax_element(vi.begin(),vi.end())”<<endl;
cout<<”*it.first=”<<*it.first<<” ,*it.second=”<<*it.second<<endl;
cout<<”*(it.first-1)=”<<*(it.first-1)<<” ,*(it.second-1)=”<<*(it.second-1)<<endl;
}
运行截图:
可以看出,firstf返回的是第一个出现的最小值的迭代器,second返回的是最后一个出现的最大值的迭代器。
——————————————————————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:coderguang@gmail.com
2014-9-18
于GDUT
——————————————————————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/stlalgorithm算法minmaxminmax-element36/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!