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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With