开发者

Adding and removing large amounts of data with std::vector [duplicate]

开发者 https://www.devze.com 2023-02-22 03:14 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to downsize std::vector?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to downsize std::vector?

It seems that std::vector will not release memory even I call pop_back(), clear() or resize().

Is there any good way to deal with this? For example, in the following code:

#include<vector>
  
using namespac开发者_JAVA百科e std;
  
int main(){
  int i, j;
  vector<int> v[10000];
  for( i=0 ; i<10000 ; i++ ){
    for( j=0 ; j<100000000 ; j++ ){
      v[i].push_back(j);
    }
    while(v[i].size()>0){
      v[i].pop_back();
    }
    v[i].resize(1);
  }
  return 0;
}

The vector will not release any memory until it finished.


std::vector grows but never shrinks. The reason is that growing is expensive, so if you shrink and then grow back it's a waste of performance.

If you really want to shrink a large vector use the swap idiom:

std::vector<T> vec;
// push push push ...
std::vector<T>(vec).swap(vec);

This doesn't guarantee the new size of vec is exactly the sum of sizes of its elements, but it should be something close. Also, C++0x's std::vector will have a shrink_to_fit() member that will do roughly that.

0

精彩评论

暂无评论...
验证码 换一张
取 消