在c++中,vector是一個十分有用的容器,下面對這個容器做一下總結。
1 基本操作
(1)頭文件#include.
(2)創建vector對象,vector vec;
(3)尾部插入數字:vec.push_back(a);
(4)使用下標訪問元素,cout<
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<iostream>
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 id<a.id;
else
{
if(length!=a.length)
return length<a.length;
else
return width<a.width;
}
}
}Rect;
int main()
{
vector<Rect> vec;
Rect rect;
rect.id=1;
rect.length=2;
rect.width=3;
vec.push_back(rect);
vector<Rect>::iterator it=vec.begin();
cout<<(*it).id<<' '<<(*it).length<<' '<<(*it).width<<endl;
return 0;
}
3 算法
(1) 使用reverse將元素翻轉:需要頭文件#include
reverse(vec.begin(),vec.end());將元素翻轉(在vector中,如果一個函數中需要兩個迭代器,
一般後一個都不包含.)
(2)使用sort排序:需要頭文件#include,
sort(vec.begin(),vec.end());(默認是按升序排列,即從小到大).
可以通過重寫排序比較函數按照降序比較,如下:
定義排序比較函數:
bool Comp(const int &a,const int &b)
{
return a>b;
}
調用時:sort(vec.begin(),vec.end(),Comp),這樣就降序排序。
出自:http://www.cnblogs.com/wang7/archive/2012/04/27/2474138.html