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);的形式。
下面的代码是可以运行的。
- #include <iostream>
- #include<vector>
- using namespace std;
- int main(){
- vector<vector<int>> test(50);
- vector<int> temp;
- test[10].push_back(1);
- cout<<test[10][0]<<endl;
- test.clear();
- for(int i=0;i<51;i++)
- test.push_back(temp);
- system("pause");
- return 0;
- }
但是这样是会越界错误的。
- #include <iostream>
- #include<vector>
- using namespace std;
- int main(){
- vector<vector<int>> test(50);
- vector<int> temp;
- test[10].push_back(1);
- cout<<test[10][0]<<endl;
- test.clear();
- for(int i=0;i<50;i++)
- test[i].push_back(1);
- system("pause");
- return 0;
- }
- for(int i=0;i<100;i++)
- test[i].push_back(1);