數組的代替品——模板類vector, array的使用

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

1 基本操做c++

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

(2)建立vector對象,vector<int> vec;函數

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

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

(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個元素string

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

(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),這樣就降序排序。

相關文章
相關標籤/搜索