简体   繁体   中英

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

无法帮助你使用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...

Feel free to point out better ways of doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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