Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.
vector也是一個數組但是它的占用的內存大小是動態變化的。當vector占用的內存滿了之后,就要重新分配內存,並且賦值原來的所有元素,為了避免頻繁的重新分配內存,遷移數據。vector實際分配的內存比你需要的內存多。比如你有10個int的數據在vector中,vector實際占用的內存是20個int的內存, 當你數據占用超過實際占用內存的比例的時候,vector就會自動重新分配內存,遷移數據. vector實際占用的內存可以用capacity()來查看
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 int main(){ 5 vector<int> ans; 6 for(int i=0; i<10; i++) ans.push_back(i); 7 ans.erase(ans.begin()+2); 8 cout<<"擦除第三個數字:"; 9 for(int j=0; j<ans.size(); j++) cout<<ans[j]<<" "; 10 ans.erase(ans.begin(), ans.begin()+2); 11 cout<<endl<<"擦除前2個數字:"; 12 for(int k=0; k<ans.size(); k++) cout<<ans[k]<<" "; 13 //盡量不要頻繁使用這個函數,會引起大量數據移動,降低程序效率 14 ans.insert(ans.begin()+1, 100); 15 cout<<endl<<"在第一位后面插入100:"; 16 for(int m=0; m<ans.size(); m++) cout<<ans[m]<<" "; 17 //vector在聲明的時候,可以申明大小和默認值 18 vector<int> temp(5, -1); 19 cout<<endl<<"temp的大小為5,默認值是-1:"; 20 for(int l=0; l<temp.size(); l++) cout<<temp[l]<<" "; 21 //resize(int n)改變vector實際儲存的數據個數, 如果n比實際個數多,則多出的位添加0,否則截取掉多余數據 22 temp.resize(8); 23 cout<<endl<<"把temp的大小改變位8:"; 24 for(int h=0; h<temp.size(); h++) cout<<temp[h]<<" "; 25 //在改變vector大小的同時還能指定多余內存的值;這種方式只適用於分配的空間比原來的多的情況 26 temp.resize(10, 1111); 27 cout<<endl<<"temp的大小改為10,並且指定多出來空間的值位11111:"; 28 for(int g=0; g<temp.size(); g++)cout<<temp[g]<<" "; 29 cout<<endl<<"獲取temp的第一個元素:"<<temp.front()<<endl<<"獲取temp的最后一個元素:"<<temp.back(); 30 //常用empty()和size函數來判斷vector是否為空,當vector為空的時候, empty()返回true, size()的值為0 31 return 0;}
此外可以配合#include<algorithm>庫中的unique函數來刪除vector中的重復元素
vector<int> ans; ans.erase(unique(ans.begin(), ans.end()), ans.end());