C++ vector 用法

來源:互聯網
上載者:User

標籤:

【轉載】 from: http://http://www.cnblogs.com/wang7/archive/2012/04/27/2474138.html

在c++中,vector是一個十分有用的容器,下面對這個容器做一下總結。

1. 基本操作

(1)標頭檔 #include<vector>.

(2)建立vector對象:vector<int> vec;

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

(4)使用下標訪問元素:cout << vec[0] << endl;  (記住下標從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個元素前面插入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,還可以是結構體。但是要注意:結構體要定義為全域的,否則會出錯。

下面是一段簡短的程式碼:

#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<algorithm>

      reverse(vec.begin(),vec.end());  將元素翻轉(在vector中,如果一個函數中需要兩個迭代器, 一般後一個都不包含).

(2) 使用sort排序:需要標頭檔#include<algorithm>

      sort(vec.begin(),vec.end());  (預設是按升序排列,即從小到大).

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

定義排序比較函數:

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

調用時:sort(vec.begin(),vec.end(),Comp); (這樣就降序排列了).

C++ vector 用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.