STL algorithm算法minmax,minmax_element(36)

minmax原型:

std::minmax

default (1)
template <class T>
  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 <class T>
  pair<T,T> minmax (initializer_list<T> il);
template <class T, class Compare>
  pair<T,T> minmax (initializer_list<T> il, Compare comp);
该函数返回一个pair,该pair的first元素的值为a,b中的最小值,second元素的值为a.b中的最大值。

使用operator<进行比較。

假设a=b,那么将返回make_pair(a,b).

对于(3)。返回初始化列表中的最小最大值的pair,假设最值多于一个。firstf返回的是第一个出现的最小值。second返回的是最后一个出现的最大值

其行为类似于:

template <class T> pair <const T&,const T&> minmax (const T& a, const T& b) {
  return (b<a) ? std::make_pair(b,a) : std::make_pair(a,b);
}
一个简单的样例:

#include <iostream>
#include <algorithm>
#include <vector>
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 <class ForwardIterator>
  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 <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void minmaxelement(){
    vector<int> vi{3,5,4,1,3,1,9,9,5};
    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

——————————————————————————————————————————————————————————————————






posted @ 2016-01-03 09:28  phlsheji  阅读(1590)  评论(0编辑  收藏  举报