vector内存容量测试

 原因: 频繁开辟一个变大小空间的情况,避免多次重复开辟空间又回收的状况。 测试了vector内存初始化重置的case. 


#include <stdio.h>
#include <vector>
#include <iostream>

int main(){
 
  std::vector<float> test(10, 0.5);
  std::cout<<"1size: "<<test.size()<<" capacity:"<<test.capacity()<<std::endl; 
  for(int i=0; i<test.size(); i++)
  {
    std::cout<<" "<<test[i]; 
  }
  std::cout<<" "<<std::endl;   

  test.clear();//清空数据保持容量
  std::cout<<"2size: "<<test.size()<<" capacity: "<<test.capacity()<<std::endl;
  for(int i=0; i<test.size(); i++)
  {
    std::cout<<" "<<test[i]; 
  }
  test.resize(6, 0.6);
  std::cout<<" "<<std::endl; 


  std::cout<<"3size: "<<test.size()<<" capacity: "<<test.capacity()<<std::endl;
    for(int i=0; i<test.size(); i++)
  {
    std::cout<<" "<<test[i]; 
  }
  std::cout<<" "<<std::endl;

  test.resize(15, 0.7);
  std::cout<<"4size: "<<test.size()<<" capacity: "<<test.capacity()<<std::endl;
  for(int i=0; i<test.size(); i++)
  {
    std::cout<<" "<<test[i]; 
  }
  std::cout<<" "<<std::endl;   
  return 0;
}
 
kint@kint:~/tmp$ g++ test2.cpp  && ./a.out 
1size: 10 capacity:10
 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 
2size: 0 capacity: 10
 
3size: 6 capacity: 10
 0.6 0.6 0.6 0.6 0.6 0.6 
4size: 15 capacity: 15
 0.6 0.6 0.6 0.6 0.6 0.6 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 0.7 

猜你喜欢

转载自blog.csdn.net/zyh821351004/article/details/114919775