我正在尝试使用 boost lambda 来避免编写琐碎的仿函数。 例如,我想使用 lambda 来访问结构的成员或调用类的方法,例如:
#include <vector>
#include <utility>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
using namespace std;
using namespace boost::lambda;
vector< pair<int,int> > vp;
vp.push_back( make_pair<int,int>(1,1) );
vp.push_back( make_pair<int,int>(3,2) );
vp.push_back( make_pair<int,int>(2,3) );
sort(vp.begin(), vp.end(), _1.first > _2.first );
当我尝试编译它时,出现以下错误:
error C2039: 'first' : is not a member of 'boost::lambda::lambda_functor<T>'
with
[
T=boost::lambda::placeholder<1>
]
error C2039: 'first' : is not a member of 'boost::lambda::lambda_functor<T>'
with
[
T=boost::lambda::placeholder<2>
]
因为 vp 包含 pair<int,int>
我认为 _1.first 应该有效。我做错了什么?
最佳答案
你想要的是类似于:
#include <boost/lambda/bind.hpp> // new header
// typedefs make code easier
typedef pair<int,int> pair_type;
typedef vector<pair_type> vector_type;
vector_type vp;
vp.push_back( make_pair(1,1) ); // don't specify template arguments!
vp.push_back( make_pair(3,2) ); // the entire point of make_pair is
vp.push_back( make_pair(2,3) ); // to deduce them.
sort(vp.begin(), vp.end(),
bind(&pair_type::first, _1) > bind(&pair_type::first, _2) );
关于c++ - 尝试使用 boost lambda,但我的代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2642868/