c++ - 尝试使用 boost lambda,但我的代码无法编译

标签 c++ compiler-errors boost-lambda

我正在尝试使用 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/

相关文章:

java - Java编译错误

c++ - 用于在堆上生成对象的函数式编程技术

C++ boost lambda 库

C++ 为 vector 设置 keyCompare 函数

c++ - 让函数指针模板参数接受右值引用是否合法?

c++ - 在 CodeLite 中链接 SFML

c++ - 使用 boost::bind 将回调发布到任务队列

c++ - 调整图像大小 OpenCV

c++ - 如何让不同的进程使用Windows 7不同的网络接口(interface)?

c++ - 如何引用静态函数作为参数传递?