欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++中vector容器的用法

 更新時(shí)間:2016年10月27日 13:44:51   作者:金河  
在c++中,vector是一個(gè)十分有用的容器。這篇文章主要介紹了C++ vector容器的用法的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下

在c++中,vector是一個(gè)十分有用的容器,下面對(duì)這個(gè)容器做一下總結(jié)。

1 基本操作

(1)頭文件#include<vector>.

(2)創(chuàng)建vector對(duì)象,vector<int> vec;

(3)尾部插入數(shù)字:vec.push_back(a);

(4)使用下標(biāo)訪問元素,cout<<vec[0]<<endl;記住下標(biāo)是從0開始的。

(5)使用迭代器訪問元素.

vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
cout<<*it<<endl;

(6)插入元素: vec.insert(vec.begin()+i,a);在第i+1個(gè)元素前面插入a;

(7)刪除元素: vec.erase(vec.begin()+2);刪除第3個(gè)元素

vec.erase(vec.begin()+i,vec.end()+j);刪除區(qū)間[i,j-1];區(qū)間從0開始

(8)向量大小:vec.size();

(9)清空:vec.clear();

2

vector的元素不僅僅可以使int,double,string,還可以是結(jié)構(gòu)體,但是要注意:結(jié)構(gòu)體要定義為全局的,否則會(huì)出錯(cuò)。下面是一段簡短的程序代碼:

#include<stdio.h>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
typedef struct rect
{
int id;
int length;
int width;
  //對(duì)于向量元素是結(jié)構(gòu)體的,可在結(jié)構(gòu)體內(nèi)部定義比較函數(shù),下面按照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將元素翻轉(zhuǎn):需要頭文件#include<algorithm>

reverse(vec.begin(),vec.end());將元素翻轉(zhuǎn)(在vector中,如果一個(gè)函數(shù)中需要兩個(gè)迭代器,

一般后一個(gè)都不包含.)

(2)使用sort排序:需要頭文件#include<algorithm>,

sort(vec.begin(),vec.end());(默認(rèn)是按升序排列,即從小到大).

可以通過重寫排序比較函數(shù)按照降序比較,如下:

定義排序比較函數(shù):

bool Comp(const int &a,const int &b)
{
return a>b;
}

調(diào)用時(shí):sort(vec.begin(),vec.end(),Comp),這樣就降序排序。

以上所述是小編給大家介紹的C++中 vector容器的用法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論