gpt4 book ai didi

c++ - not2 STL 否定符

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:34 24 4
gpt4 key购买 nike

学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com