vendredi 2 juin 2017

Avoid the reallocation of a vector when its dimension has to be incremented by one element

I have a

vector< pair<vector<double> , int> samples;

This vector will contain a number of elements. For efficiency rason I initialize it in this way:

vector< pair<vector<double> , int> samples(1000000);

I know the size in advance (not a compile-time) that I get from another container. The problem is that I have to decrease of 1 element the dimension of vector. Indeed, this case isn't a problem because resize with smaller dimension than the initial no do reallocation.I can do

samples.resize(999999);

The problem is that in some cases rather than decrease the dimension of 1 element I have to increment the dimension of an element. If I do

samples.resize(1000001);

there is the risk of do reallocation that I want avoid for efficiency rasons. I ask if is a possible solution to my problem do like this:

vector< pair<vector<double> , int> samples;
samples.reserve(1000001);
samples.resize(1000000);
.
. Elaboration that fill samples 
.
samples.resize(1000001); //here I don't want reallocation

or if there are better solutions? Thanks in advance!

(I'm using C++11 compiler)

Aucun commentaire:

Enregistrer un commentaire