简体   繁体   English

如何使用boost lambda来填充带有新对象的指针向量

[英]How to use boost lambda to populate a vector of pointers with new objects

I've recently started using boost lambda and thought I'd try and use it in places where it will/should make things easier to read. 我最近开始使用boost lambda并且认为我会尝试在可以/易于阅读的地方使用它。

I have some code similar to the following 我有一些类似于以下的代码

std::vector< X * > v;
for ( int i = 0 ; i < 20 ; ++i )
    v.push_back( new X() );

and later on, to delete it... 然后,删除它...

std::for_each( v.begin(), v.end(), boost::lamda::delete_ptr() );

Which neatly tidies up. 整齐整理。

However, I thought I'd have a go at "lambda-ising" the population of the vector using lambda... That's then the fireworks started... 然而,我以为我会在“lambda-ising”中使用lambda进行矢量填充...那就是烟花开始......

I tried.. 我试过了..

std::generate_n( v.begin(), 20, _1 = new X() );

but this threw all kinds of compiler errors. 但这引发了各种编译器错误。

Any ideas which is the best "lambda" way to achieve this. 任何想法都是实现这一目标的最佳“lambda”方式。

Thx Mark. 谢谢马克。

Here's a code snippet that does what you want: 这是一个代码片段,可以满足您的需求:

#include <algorithm>
#include <vector>

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/construct.hpp>

typedef int X;

int main() {
  std::vector<X*> v;
  std::generate_n( std::back_inserter(v), 20, boost::lambda::new_ptr<X>() );
  std::for_each( v.begin(), v.end(), boost::lambda::delete_ptr() );
}

You might want to consider using boost::ptr_vector though, as using a std::vector with dynamically allocated pointers in an exception safe way isn't easy. 您可能想要考虑使用boost :: ptr_vector,因为使用带有动态分配指针的std :: vector以异常安全的方式并不容易。

You might consider: 你可能会考虑:

static const int PtrVectorSize = 20;

// ....
v.resize(PtrVectorSize);
generate_n(v.begin(), PtrVectorSize, new_ptr<X>());

Also, you could use boost::ptr_vector and save your self the deletes. 此外,您可以使用boost :: ptr_vector并保存自己的删除。

无法帮助你使用lambda,但是你看过boost :: assign库吗?

Ok, After an extra bit of playing I came up with this... 好的,经过一段时间的游戏,我想出了这个......

std::generate_n( std::back_insert_iterator< std::vector< X* > >( ip ), 20, new_ptr< X >() ) );

I'm not quite sure this is as elegant. 我不太确定这是优雅的。 From a programming perspective, it may be, but from a "in-6-months-time-will-I-know-what-this-was-meant-to-do" perspectice, I'm not sure... 从编程的角度来看,它可能是,但是从“6个月的时间 - 我知道 - 这是什么意思 - 做什么”的说法来看,我不确定......

Feel free to point out better ways of doing this. 请随意指出更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM