C++是C語言的繼承,它既可以進行C語言的過程化程序設計,又可以進行以抽象數據類型為特點的基于對象的程序設計,還可以進行以繼承和多態為特點的面向對象的程序設計。C++擅長面向對象程序設計的同時,還可以進行基于過程的程序設計,因而C++就適應的問題規模而論,大小由之。c++ vector是在c++中開發過程中c++ vector作為一個十分有用的容器,許多朋友還不是很清楚c++ vector用法,不知道c++ vector到底有什么優秀的用法,不用著急一起來看看c++ vector用法詳解來增加自身對c++ vector的了解吧。
1:基本操作
(1)頭文件#includevector.
(2)創建vector對象,vectorint vec;
(3)尾部插入數字:vec.push_back(a);
(4)使用下標訪問元素,coutvec[0]endl;記住下標是從0開始的。
(5)使用迭代器訪問元素.
vectorint::iterator it;
for(it=vec.begin();it!=vec.end();it++)
cout*itendl;
(6)插入元素: vec.insert(vec.begin()+i,a);在第i+1個元素前面插入a;
(7)刪除元素: vec.erase(vec.begin()+2);刪除第3個元素
vec.erase(vec.begin()+i,vec.end()+j);刪除區間[i,j-1];區間從0開始
(8)向量大小:vec.size();
(9)清空:vec.clear();
2:vector的元素不僅僅可以使int,double,string,還可以是結構體,但是要注意:結構體要定義為全局的,否則會出錯。
#includestdio.
#includealgorithm
#includevector
#includeiostream
using namespace std;
typedef struct rect
{
int id;
int length;
int width;
//對于向量元素是結構體的,可在結構體內部定義比較函數,下面按照id,length,width升序排序。
bool operator (const rect &a) const
{
if(id!=a.id)
return ida.id;
else
{
if(length!=a.length)
return lengtha.length;
else
return widtha.width;
}
}
}Rect;
int main()
{
vectorRect vec;
Rect rect;
rect.id=1;
rect.length=2;
rect.width=3;
vec.push_back(rect);
vectorRect::iterator it=vec.begin();
cout(*it).id' '(*it).length' '(*it).widthendl;
return 0;
}
3:算法
(1) 使用reverse將元素翻轉:需要頭文件#includealgorithm
reverse(vec.begin(),vec.end());將元素翻轉(在vector中,如果一個函數中需要兩個迭代器,
一般后一個都不包含.)
(2)使用sort排序:需要頭文件#includealgorithm,
sort(vec.begin(),vec.end());(默認是按升序排列,即從小到大).
可以通過重寫排序比較函數按照降序比較,如下:
定義排序比較函數:
bool Comp(const int &a,const int &b)
{
return ab;
}
調用時:sort(vec.begin(),vec.end(),Comp),這樣就降序排序。
希望大家在這里都能獲得自己需要的東西。
新聞熱點
疑難解答
圖片精選