Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I pay for default construction here and if so can I avoid it

Tags:

c++

c++11

boost

In the case where T is expensive to construct I'd like to know if I pay for default construction in the following case (I think I do)

std::function< T() > make_t;
std::vector< T > t( 100000 );
std::generate( t.begin(), t.end(), make_T );

If I do have to pay for it can I avoid it? I wanted to write something like

std::function< T() > make_t;
std::vector< T > t;
t.reserve( 100000 );
std::generate( t.begin(), t.end(), make_T );

But that does not work because it does not move t.end() to the end of what is reserved. Is the following safe/advisable/correct?

std::function< T() > make_t;
std::vector< T > t;
t.reserve( 100000 );
std::generate( t.begin(), t.begin() + 100000, make_T );

I also thought I might be able to use a back_inserter but the interface is right for what I have (I have a function that generates a new T object every time it is accessed not a pair of iterators to a range).

C++0x solutions preferred to C++03 solutions (i.e., ones that leverage the new standard if there's a better way to do it there) preferred to solution that need to use boost.

like image 269
bpw1621 Avatar asked Dec 21 '22 11:12

bpw1621


1 Answers

std::function< T() > make_t;
std::vector< T > t;
int const count = 100000;
t.reserve( count );
std::generate_n( std::back_inserter(t), count, make_T );

std::back_inserter is in <iterator>.

like image 59
Luc Danton Avatar answered Dec 29 '22 01:12

Luc Danton