将值向量复制到一行中的对向量
我有以下类型:
struct X { int x; X( int val ) : x(val) {} };
struct X2 { int x2; X2() : x2() {} };
typedef std::pair<X, X2> pair_t;
typedef std::vector<pair_t> pairs_vec_t;
typedef std::vector<X> X_vec_t;
我需要使用 X_vec_t
中的值初始化 pairs_vec_t
的实例。我使用以下代码,它按预期工作:
int main()
{
pairs_vec_t ps;
X_vec_t xs; // this is not empty in the production code
ps.reserve( xs.size() );
{ // I want to change this block to one line code.
struct get_pair {
pair_t operator()( const X& value ) {
return std::make_pair( value, X2() ); }
};
std::transform( xs.begin(), xs.end(), back_inserter(ps), get_pair() );
}
return 0;
}
我想做的是使用 boost::bind
将复制块减少到一行。此代码不起作用:
for_each( xs.begin(), xs.end(), boost::bind( &pairs_vec_t::push_back, ps, boost::bind( &std::make_pair, _1, X2() ) ) );
我知道它为什么不起作用,但我想知道如何使其工作而不声明额外的函数和结构?
I have the following types:
struct X { int x; X( int val ) : x(val) {} };
struct X2 { int x2; X2() : x2() {} };
typedef std::pair<X, X2> pair_t;
typedef std::vector<pair_t> pairs_vec_t;
typedef std::vector<X> X_vec_t;
I need to initialize instance of pairs_vec_t
with values from X_vec_t
. I use the following code and it works as expected:
int main()
{
pairs_vec_t ps;
X_vec_t xs; // this is not empty in the production code
ps.reserve( xs.size() );
{ // I want to change this block to one line code.
struct get_pair {
pair_t operator()( const X& value ) {
return std::make_pair( value, X2() ); }
};
std::transform( xs.begin(), xs.end(), back_inserter(ps), get_pair() );
}
return 0;
}
What I'm trying to do is to reduce my copying block to one line with using boost::bind
. This code is not working:
for_each( xs.begin(), xs.end(), boost::bind( &pairs_vec_t::push_back, ps, boost::bind( &std::make_pair, _1, X2() ) ) );
I know why it is not working, but I want to know how to make it working without declaring extra functions and structs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西?
我现在无法检查,但如果从记忆中正确回忆起,上述内容是有效的。
something like this?
I cant check at the moment, but if recalled correctly from memory, the above is valid.
无需升压。
std::bind2nd
已被弃用,取而代之的是 Boost 采用的std::bind
,但目前它是标准。如果您确实有Boost,
插入
一个范围(transform_iterator
)比迭代push_back
或预尺寸:单行线怎么样?
No Boost needed.
std::bind2nd
is being deprecated in favor ofstd::bind
adopted from Boost, but for now it's the standard.If you do have Boost, it's more efficient to
insert
a range (oftransform_iterator
) than iterate onpush_back
or pre-size:How's that for a one-liner?