mercredi 28 juin 2017

Is it possible that resizing an std::vector reduces its capacity?

I have this container: std::vector< std::tuple,std::vector > > rvec1 where each inner vector contains a number of elements. After some computations I resize the inner vectors. The problem is that when I measure the capacity of each vector it seems that it decreases. Is this normal to happen?

Here is the function where I resize the vectors:

int merge_vector_elements(std::vector< std::tuple<std::vector<int>,std::vector<float> > >& rvec1){

        long totalCapacity = 0;
        for(auto itr : rvec1){
          totalCapacity += std::get<0>(itr).capacity();
          totalCapacity += std::get<1>(itr).capacity();
        }
        std::cout<<"Total Capacity before merge / shrink: "<<totalCapacity<<std::endl;

        int nnz = 0;
        for (msize_t i=0; i<rvec1.size(); i++){
          int count = 0;
           for(msize_t j = 0; j < std::get<0>(rvec1[i]).size(); ++j, ++count){
             std::get<0>(rvec1[i])[count] = std::get<0>(rvec1[i])[j];
             std::get<1>(rvec1[i])[count] = std::get<1>(rvec1[i])[j];
             while((j+1 != std::get<0>(rvec1[i]).size()) && std::get<0>(rvec1[i])[count] == std::get<0>(rvec1[i])[j+1]){  
               std::get<1>(rvec1[i])[count] += std::get<1>(rvec1[i])[j+1];
               j++;
             } 
           }
           std::get<0>(rvec1[i]).resize(count);
           //std::get<0>(rvec1[i]).shrink_to_fit();
           std::get<1>(rvec1[i]).resize(count);
           //std::get<1>(rvec1[i]).shrink_to_fit();
           nnz += count;
        }
        totalCapacity = 0;
        for(auto itr : rvec1){
          totalCapacity += std::get<0>(itr).capacity();
          totalCapacity += std::get<1>(itr).capacity();
        }
        std::cout<<"Total Capacity after merge / shrink: "<<totalCapacity<<std::endl;

        return nnz;
      }

The results are:

Total Capacity before merge / shrink: 254396100

Total Capacity after merge / shrink: 107010297

So the capacity seems to be affected.

Also some sample code where the resize doesn't affect the capacity of the vector.

int main(){

  long bufferSize = 1000000000;

  std::vector<double> newVec(bufferSize);

  for(int i=0; i<bufferSize; i++){
      newVec[i] = i * 8.99;
  }

  std::cout<<"Capacity before resize: "<<newVec.capacity()<<std::endl;
  newVec.resize(bufferSize / 2);

  // newVec.shrink_to_fit();
  std::cout<<"Capacity after resize: "<<newVec.capacity()<<std::endl;

  return 0;
}

Compiling with gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0

Aucun commentaire:

Enregistrer un commentaire