vendredi 6 décembre 2019

C++: std::generate in constructor

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. 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.

Aucun commentaire:

Enregistrer un commentaire