C++STL——vector03

1.vector::clear(),容器vector的clear函数详解。

转自:https://blog.csdn.net/Hk_john/article/details/72463318

最近经常用到vector容器,发现它的clear()函数有点意思,经过验证之后进行一下总结。

clear()函数的调用方式是,vector<datatype> temp(50);//定义了50个datatype大小的空间。temp.clear();

作用:将会清空temp中的所有元素,包括temp开辟的空间(size),但是capacity会保留,即不可以以temp[1]这种形式赋初值,只能通过temp.push_back(value)的形式赋初值。

同样对于vector<vector<datatype> > temp1(50)这种类型的变量,使用temp1.clear()之后将会不能用temp1[1].push_back(value)进行赋初值,只能使用temp1.push_back(temp);的形式。

下面的代码是可以运行的。

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include<vector>  
  3.   
  4. using namespace std;  
  5.   
  6. int main(){  
  7.   
  8.     vector<vector<int>> test(50);  
  9.     vector<int> temp;  
  10.     test[10].push_back(1);  
  11.     cout<<test[10][0]<<endl;  
  12.     test.clear();  
  13.   
  14.   
  15.     for(int i=0;i<51;i++)  
  16.         test.push_back(temp);  
  17.   
  18.     system("pause");  
  19.     return 0;  
  20. }  

但是这样是会越界错误的。


[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include<vector>  
  3.   
  4. using namespace std;  
  5.   
  6. int main(){  
  7.   
  8.     vector<vector<int>> test(50);  
  9.     vector<int> temp;  
  10.     test[10].push_back(1);  
  11.     cout<<test[10][0]<<endl;  
  12.     test.clear();  
  13.   
  14.     for(int i=0;i<50;i++)  
  15.         test[i].push_back(1);  
  16.   
  17.     system("pause");  
  18.     return 0;  
  19. }  
并且即使我们使用

[cpp]  view plain  copy
  1. for(int i=0;i<100;i++)  
  2.     test[i].push_back(1);  
都是可以的,因为size已经被清处了。

猜你喜欢

转载自blog.csdn.net/qq_40794602/article/details/80216342