尝试使用 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 contains pair
我认为 _1.first 应该有效。我做错了什么?
I am trying to use boost lambda to avoid having to write trivial functors.
For example, I want to use the lambda to access a member of a struct or call a method of a class, eg:
#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 );
When I try and compile this I get the following errors:
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>
]
Since vp contains pair<int,int>
I thought that _1.first should work. What I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想要的是类似于:
What you want is something akin to:
根据这个,我相信语法是
但是,我想指出(不是那么明显?) -
sort(vp.begin(), vp.end());
基本上会做同样的事情。默认情况下,pair 按第一个参数排序,然后按第二个参数排序。由于您使用的是sort
(这并不稳定),因此您将先按first
对所有对进行排序,然后对具有相同first 的对进行排序
将或多或少地按随机顺序排列。如果您想在第一个元素相等时保留顺序,则应使用
stable_sort
代替。According to this, I believe the syntax is
However, I'd like to point out the (not so?) obvious --
sort(vp.begin(), vp.end());
will basically do the same thing.pair
s are by default sorted by their first argument, then by the second. Since you're usingsort
(which is not stable), you're going to have all the pairs sorted byfirst
, and then the pairs with equalfirst
are going to be in more or less random order.If you want to preserve the order when the first elements are equal, you should use
stable_sort
instead.