Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 331
ScaryAardvark Avatar asked Jan 11 '10 16:01

ScaryAardvark


1 Answers

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.

like image 58
JoeG Avatar answered Sep 18 '22 22:09

JoeG