I pay for the default construction here, and if so, can I avoid it?

In the case where T is expensive to build, I would like to know if I will pay for the default build 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 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 this does not work, because it does not move t.end () to the end of the reserved. Is the following safe / appropriate / 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 that I could use back_inserter, but the interface is suitable for what I have (I have a function that generates a new T object every time a non-iterator pair accesses it).

C ++ 0x solutions are preferable to C ++ 03 solutions (i.e. those that use the new standard, if there is a better way to do it there) prefer the solution that you need to use boost.

+4
source share
3 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 located in <iterator> .

+8
source

You can fix your second solution with the std::back_inserter , which does push_back for you:

 std::vector< T > t; t.reserve(100000); std::generate_n(std::back_inserter(t), 100000, make_t); 
+3
source

You will pay for the default construction if you are afraid. You must prove it yourself by checking the generated assembly code on your specific platform.

I would do a shared_ptr<T> vector trick, not a simple T , then the rest is easy. It also makes it easier to move objects later if you need it.

0
source

All Articles