not2 stl negator

GBB*_*BBL 1 c++ stl

学习STL我试图否定一个没有问题但是有问题的算子.这是一个例子:

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
struct  mystruct : binary_function<int,int,bool> {
 bool operator() (int i,int j) { return i<j; }
};

template <class T>
class generatore 
{
public:
 generatore (T  start = 0, T  stp = 1) : current(start), step(stp)
 { }
 T  operator() () { return current+=step; }
private:
 T  current;
 T  step;
};


int main () {
 vector<int> first(10);

generate(first.begin(), first.end(), generatore<int>(10,10) ); 
cout << "Smallest element " << *min_element(first.begin(), first.end(),mystruct() ) << endl;
 cout << "Smallest element:  " << *max_element(first.begin(), first.end(),not2(mystruct())) << endl;

}
Run Code Online (Sandbox Code Playgroud)

最后一行代码不能用g ++编译.可能是一个愚蠢的错误,但在哪里?

Own*_*loo 5

struct  mystruct : binary_function<int,int,bool> {
        bool operator() (int i,int j) const // add a const here
            { return i<j; }
};
Run Code Online (Sandbox Code Playgroud)

原因:

在这一行:

cout << "Smallest element:  " << *max_element(first.begin(), first.end(),not2(mystruct())) << endl
Run Code Online (Sandbox Code Playgroud)

not2(mystruct())将返回一个std::binary_negate:

template<class AdaptableBinaryPredicate>
binary_negate<AdaptableBinaryPredicate> not2( P const& pred ) {
        return binary_negate<AdaptableBinaryPredicate>(pred);
}
Run Code Online (Sandbox Code Playgroud)

在std :: binary_negate中,调用操作符是const非静态成员函数

template <class AdaptableBinaryPredicate>
class binary_negate
        : public binary_function
                     <typename AdaptableBinaryPredicate::first_argument_type
                     ,typename AdaptableBinaryPredicate::second_argument_type
                     ,bool>
{
        AdaptableBinaryPredicate pred_;
public:
        explicit binary_negate ( const AdaptableBinaryPredicate& pred )
                : pred_ (pred) {} // holds the original predication

         bool operator() (const typename Predicate::first_argument_type& x,
                          const typename Predicate::second_argument_type& y
                         ) const  // the calling operator is const
         { return !pred_(x,y);    // call original predication and negate it!

           // the calling operator of binary_negate is const 
           //   so pred_ in this member has const qualify
           //   and the calling operator of pred_ must be const
         }
};
Run Code Online (Sandbox Code Playgroud)