c++ vector 常用函數(shù)示例解析
c++ vector 常用函數(shù)
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也是一個數(shù)組但是它的占用的內(nèi)存大小是動態(tài)變化的。當(dāng)vector占用的內(nèi)存滿了之后,就要重新分配內(nèi)存,并且賦值原來的所有元素,為了避免頻繁的重新分配內(nèi)存,遷移數(shù)據(jù)。vector實際分配的內(nèi)存比你需要的內(nèi)存多。比如你有10個int的數(shù)據(jù)在vector中,vector實際占用的內(nèi)存是20個int的內(nèi)存, 當(dāng)你數(shù)據(jù)占用超過實際占用內(nèi)存的比例的時候,vector就會自動重新分配內(nèi)存,遷移數(shù)據(jù). vector實際占用的內(nèi)存可以用capacity()來查看
#include<iostream> #include<vector> using namespace std; int main(){ vector<int> ans; for(int i=0; i<10; i++) ans.push_back(i); ans.erase(ans.begin()+2); cout<<"擦除第三個數(shù)字:"; for(int j=0; j<ans.size(); j++) cout<<ans[j]<<" "; ans.erase(ans.begin(), ans.begin()+2); cout<<endl<<"擦除前2個數(shù)字:"; for(int k=0; k<ans.size(); k++) cout<<ans[k]<<" "; //盡量不要頻繁使用這個函數(shù),會引起大量數(shù)據(jù)移動,降低程序效率 ans.insert(ans.begin()+1, 100); cout<<endl<<"在第一位后面插入100:"; for(int m=0; m<ans.size(); m++) cout<<ans[m]<<" "; //vector在聲明的時候,可以申明大小和默認值 vector<int> temp(5, -1); cout<<endl<<"temp的大小為5,默認值是-1:"; for(int l=0; l<temp.size(); l++) cout<<temp[l]<<" "; //resize(int n)改變vector實際儲存的數(shù)據(jù)個數(shù), 如果n比實際個數(shù)多,則多出的位添加0,否則截取掉多余數(shù)據(jù) temp.resize(8); cout<<endl<<"把temp的大小改變位8:"; for(int h=0; h<temp.size(); h++) cout<<temp[h]<<" "; //在改變vector大小的同時還能指定多余內(nèi)存的值;這種方式只適用于分配的空間比原來的多的情況 temp.resize(10, 1111); cout<<endl<<"temp的大小改為10,并且指定多出來空間的值位11111:"; for(int g=0; g<temp.size(); g++)cout<<temp[g]<<" "; cout<<endl<<"獲取temp的第一個元素:"<<temp.front()<<endl<<"獲取temp的最后一個元素:"<<temp.back(); //常用empty()和size函數(shù)來判斷vector是否為空,當(dāng)vector為空的時候, empty()返回true, size()的值為0 return 0;}
此外可以配合#include<algorithm>庫中的unique函數(shù)來刪除vector中的重復(fù)元素
vector<int> ans; ans.erase(unique(ans.begin(), ans.end()), ans.end());
到此這篇關(guān)于c++ vector 常用函數(shù)示例解析的文章就介紹到這了,更多相關(guān)c++ vector 常用函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用C/C++讀取matlab中.mat格式數(shù)據(jù)的操作
這篇文章給大家介紹了使用C/C++讀取matlab中.mat格式數(shù)據(jù)的操作,文中通過圖文結(jié)合的方式介紹的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-12-12C++數(shù)據(jù)結(jié)構(gòu)之實現(xiàn)循環(huán)順序隊列
這篇文章主要介紹了 C++數(shù)據(jù)結(jié)構(gòu)之實現(xiàn)循環(huán)順序隊列的相關(guān)資料,需要的朋友可以參考下2017-01-01