min_element:
template<class FwdIt> FwdIt min_element(FwdIt first, FwdIt last);
返回区间范围[first,last) 中最小元素的迭代器,以“< ”作比较器。 最小指没有元素比它小,而不是它比别的不同元素都小 因为即便a!= b, a<b 和b<a有可能都不成立.
template<class ForwardIt>
ForwardIt min_element(ForwardIt first, ForwardIt last)
{
if (first == last) return last;
ForwardIt smallest = first;
++first;
for (; first != last; ++first) {
if (*first < *smallest) {
smallest = first;
}
}
return smallest;
}
template<class ForwardIt, class Compare>
ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp)
{
if (first == last) return last;
ForwardIt smallest = first;
++first;
for (; first != last; ++first) {
if (comp(*first, *smallest)) {
smallest = first;
}
}
return smallest;
}
我们会发现其中smallest存在比较项的右边;
max_element:
template<class FwdIt> FwdIt max_element(FwdIt first, FwdIt last);
返回[first,last) 中最大元素(它不小于任何其他元素,但不见得其他不 同元素都小于它)的迭代器,以“< ”作比较器。
源码实现:
来自cppreference上的源码实现1:
template<class ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last)
{
if (first == last) {
return last;
}
ForwardIt largest = first;
++first;
for (; first != last; ++first) {
if (*largest < *first) {
largest = first;
}
}
return largest;
}
template<class ForwardIt, class Compare>
ForwardIt max_element(ForwardIt first, ForwardIt last,
Compare comp)
{
if (first == last) {
return last;
}
ForwardIt largest = first;
++first;
for (; first != last; ++first) {
if (comp(*largest, *first)) {
largest = first;
}
}
return largest;
}
我们会发现largest在比较项的左边。
min_element与max_element综合运用
示例1:
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
int num[]={5,2,0,1,3,1,4};
cout<<"最小值是 "<<*min_element(num,num+7)<<endl;
cout<<"最大值是 "<<*max_element(num,num+7)<<endl;
return 0;
}
示例2:(中国MOOC,北大–面向对象程序设计)
#include <iostream>
#include <algorithm>
using namespace std;
class A {
public:
int n;
A(int i):n(i) { }
};
bool operator<( const A & a1, const A & a2) {
cout << "< called,a1=" << a1.n << " a2=" << a2.n << endl;
if( a1.n == 3 && a2.n == 7)
return true;
return false;
}
int main()
{
A aa[] = { 3,5,7,2,1};
cout << min_element(aa,aa+5)->n << endl;
cout << max_element(aa,aa+5)->n << endl;
return 0;
}
执行效果
然后根据前文的源码的分析可以知道为什么输出的值会是这样的了
第一:
输出最小值的过程中,由于最小值一直在比较项的右侧,那么当返回true的时候就会更新最小值,
但是直到1 < 3之后都不成立,那么最小值还是最先的初始值3;
第二:
输出最大值的过程中,由于最大值一直在比较项的左侧,那么largest < *iter,一直会返回false,
直到a1.n == 3和a2.n == 7,那么此时返回true,更新最大值使得largest = 7。
参考:
源码来源于网络,已标出处,此处只进行代码原因分析,仅供分析使用。