mardi 1 mars 2016

Reserving sub vectors while constructing

I have this:

size_t n = 100;
std::vector<std::vector<foo>> v(n);

The count of the sub vectors is dynamic but known. However, the number of items in each vector is not known but I have an estimation about it so I want to reserve the sub vectors before start pushing back into them. What I am currently doing is:

size_t estimated_size = 1000;
for (auto& sub_vector: v){
   sub_vector.reserve(estimated_size);
}

Is there a better way? Like doing it while constructing?

P.S. This is not an option:

size_t n = 100;
size_t estimated_size = 1000;
std::vector<std::vector<foo>> v(n, std::vector<foo>(estimated_size));

I just want to reserve without constructing because foo is costy to be constructed twice.

Aucun commentaire:

Enregistrer un commentaire