vector::clear(),容器vector的clear函式詳解。
阿新 • • 發佈:2019-01-01
最近經常用到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);
都是可以的,因為size已經被清處了。