How to use boost lambda to populate a pointer vector with new objects

I recently started using boost lambda and thought that I would try and use it in those places where it will / should facilitate reading.

I have a code similar to the following

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

and then to remove it ...

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

Which neatly cleans.

However, I thought that I would have a โ€œlambda-livingโ€ population of a vector using lambda ... That then the fireworks started ...

I tried..

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

but this gave rise to all kinds of compiler errors.

Any ideas that are the best way to "lambda" to achieve this.

thanks Mark.

+5
source share
4 answers

, , :

#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() );
}

, boost:: ptr_vector, std::vector .

+9

:

static const int PtrVectorSize = 20;

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

, boost:: ptr_vector .

+4

, boost:: assign library?

0

, ...

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

, . , " 6 ---- ", ...

.

0

All Articles