开发者

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.

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 populatio开发者_运维百科n of the vector using lambda... That's then the fireworks started...

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.

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.


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.


Can't help you with lambda, but have you looked at boost::assign library?


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...

Feel free to point out better ways of doing this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜