c中vector的用法
c中vector的用法的用法你知道嗎?下面小編就跟你們詳細介紹下c中vector的用法的用法,希望對你們有用。
c中vector的用法的用法如下:
1 基本操作
(1)頭文件#include<vector>.
(2)創建vector對象,vector<int> vec;
(3)尾部插入數字:_back(a);
(4)使用下標訪問元素,cout<<vec[0]<<endl;記住下標是從0開始的。
(5)使用迭代器訪問元素.
vector<int>::iterator it;
for(it=n();it!=();it++)
cout<<*it<<endl;
(6)插入元素: rt(n()+i,a);在第i+1個元素前面插入a;
(7)刪除元素: e(n()+2);刪除第3個元素
e(n()+i,()+j);刪除區間[i,j-1];區間從0開始
(8)向量大小:();
(9)清空:r();
2
vector的元素不僅僅可以使int,double,string,還可以是結構體,但是要注意:結構體要定義爲全局的,否則會出錯。下面是一段簡短的程序代碼:
複製代碼
#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!=)
return id<;
else
{
if(length!=th)
return length<th;
else
return width<h;
}
}
}Rect;
int main()
{
vector<Rect> vec;
Rect rect;
=1;
th=2;
h=3;
_back(rect);
vector<Rect>::iterator it=n();
cout<<(*it)<<' '<<(*it)th<<' '<<(*it)h<<endl;
return 0;
}
複製代碼
3 算法
(1) 使用reverse將元素翻轉:需要頭文件#include<algorithm>
reverse(n(),());將元素翻轉(在vector中,如果一個函數中需要兩個迭代器,
一般後一個都不包含.)
(2)使用sort排序:需要頭文件#include<algorithm>,
sort(n(),());(默認是按升序排列,即從小到大).
可以通過重寫排序比較函數按照降序比較,如下:
定義排序比較函數:
bool Comp(const int &a,const int &b)
{
return a>b;
}
調用時:sort(n(),(),Comp),這樣就降序排序。