c++ - not2 STL 否定符

标签 c++ stl

学习 STL 我曾尝试用 not2 否定仿函数,但遇到了问题。 这是示例:

#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;

}

最后一行代码无法使用 g++ 进行编译。可能是一个愚蠢的错误,但在哪里?

最佳答案

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

原因:

在这一行中:

cout << "Smallest element:  " << *max_element(first.begin(), first.end(),not2(mystruct())) << endl

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

template<class AdaptableBinaryPredicate>
binary_negate<AdaptableBinaryPredicate> not2( P const& pred ) {
        return binary_negate<AdaptableBinaryPredicate>(pred);
}

在 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
         }
};

关于c++ - not2 STL 否定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1861232/

相关文章:

C++:反向排序对,其中包含自定义值

c++ - 从 C++ 到 Perl

c++ - for循环的范围内是什么类型?

c++ - 交换 std::vector 作为函数参数

c++ - 使用 std::ifstream、std::istream_iterator 和 std::copy 不读取整个文件

c++ - 在 Linux 上编译错误但在 MacOSX 上没有

c++ - Qt 未定义对 `vtable for Msnger' 的引用

c++ - 使用 STL 在 C++ 中对字符串进行标记

c++ - 模板函数中 STL 容器的默认参数

c++ - std::map 是否自动平衡自身