Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: std::generate in constructor

Tags:

c++

c++11

I like to use std::generate for creating std::vectors. I think it is a fairly clean approach:

std::vector<Foo> v(5);
std::generate(v.begin(), v.end(), generator );

However, from a performance point of view, this doesn't seem great though since we allocate and initialize all of the vector elements, and then go back and replace them. Ideally, there would be a constructor that took a size and a generator function, but there doesn't seem to be one (something like v(5, generator)). Am I missing something obvious?

For cases where one is really concerned about performance (and where construction is expensive), one can do something like this:

std::vector<Foo> v;
v.reserve(5);
for (size_t i = 0 ; i < 5 ; ++i)
   v.emplace_back(..);

Another alternative would be to use a back inserter or something like that, but that would dynamically resize the vector, which also seems far from ideal.

To be clear, the size is not a compile-time argument, so I can't use an std::array. Furthermore, I would strongly prefer to stay away from raw arrays or pointers (where one could perhaps allocate memory with initializing the memory).

A C++11 solution would be preferred, but a C++14 solution would perhaps also be feasible.

like image 610
bremen_matt Avatar asked Jun 29 '26 00:06

bremen_matt


1 Answers

This look like a use case for the std::generate_n algorithm. It accepts an output iterator (such as a back_insert_iterator) and a size. If we reserve the size in advance, we can generate the elements with a generator without reallocation.

std::vector<Foo> v;
v.reserve(5);
std::generate_n(std::back_inserter(v), 5, generator);
like image 67
StoryTeller - Unslander Monica Avatar answered Jun 30 '26 13:06

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!