这是以前的帖子中关于max和min函数的回复,有的地方不懂
SummaryFinds and returns the maximum of a pair of values.Synopsis#include <algorithm>
template <class T>
 const T& max(const T&, const T&);
template <class T, class Compare>
 const T& max(const T&, const T&, Compare);DescriptionThe max algorithm determines and returns the maximum of a pair of values. The optional argument Compare defines a comparison function that can be used in place of the default operator<.max returns the first argument when the arguments are equal.Example//
// max.cpp
//
 #include <algorithm> 
 #include <iostream>
 #include <functional>
 using namespace std;
 int main(void)
 { 
   double d1 = 10.0, d2 = 20.0; 
 
   // Find minimum 
   double val1 = min(d1, d2);
   // val1 = 10.0 这里不明白,为啥min函数要返回最大值呢
   // the greater comparator returns the greater of the
   // two values.     
   double val2 = min(d1, d2, greater<double>());
   // val2 = 20.0;
 
   // Find maximum
   double val3 = max(d1, d2);
   // val3 = 20.0; 
   // the less comparator returns the smaller of 
   // the two values.
   // Note that, like every comparison in the STL, max is 
   // defined in terms of the < operator, so using less here
   // is the same as using the max algorithm with a default
   // comparator.
这里为啥还是返回最大值呢
   double val4 = max(d1, d2, less<double>());
   // val4 = 20 
   cout << val1 << " " << val2 << " " 
        << val3 << " " << val4 << endl;
   return 0;
 }Program Output10 20 20 20See Alsomax_element, min, min_element

解决方案 »

  1.   

    stl中 less 和 max 的实现
    template <class _Tp>
    struct less : public binary_function<_Tp,_Tp,bool> 
    {
      bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; }
    };template <class _Tp, class _Compare>
    inline const _Tp& (max)(const _Tp& __a, const _Tp& __b, _Compare __comp) {
      return __comp(__a, __b) ? __b : __a;
    }template <class _Tp>
    inline const _Tp& (max)(const _Tp& __a, const _Tp& __b) {  return  __a < __b ? __b : __a; }若用less 则max(d1,d2)和max(d1,d2,less<double>())中d1,d2进行相同的比较,若用greater可以得到最小值