Vector memory capacity test

 Reason: Frequently open up a variable size space, avoiding the situation of repeatedly opening up space and recycling it. Tested the case of vector memory initialization reset. 


#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 

 

Guess you like

Origin blog.csdn.net/zyh821351004/article/details/114919775