c++中vector的使用方法

在c++中,vector的作用是:它能夠像容器一樣存放各種類型的對象,簡單地說,vector是一個能夠存放任意類型的動態數組,能夠增加和壓縮數據。

1 、基本操作


#include<iostream>  
#include<vector>        //頭文件 
#include<string>  
#include<algorithm>  
using namespace std;  
int main() 
{   

    vector<int> vec;        //創建vector對象  
    //vector<vector<Point2f> > points; //定義一個二維數組
    //points[0].size();  //指第一行的列數

    vec.push_back(1);
    vec.push_back(1);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(1);        //尾部插入數字
    //vec.insert(vec.begin()+i,a);//在第i+1個元素前面插入a;
    cout<<vec[0]<<endl;         //記住下標是從0開始的

    vector<int>::iterator itr = vec.begin();//使用迭代器訪問元素

    while ( itr != vec.end())
    {    
       if (1 == *itr)
       {
           itr = vec.erase(itr);            //刪除元素
           //vec.erase(vec.begin()+2);//刪除第3個元素
           //vec.erase(vec.begin()+i,vec.end()+j);//刪除區間[i,j-1];區間從0開始
       }
       else
          ++itr;
    }


    for (itr =vec.begin(); itr != vec.end(); itr++)//使用begin和end來循環  
    {
        cout << *itr << endl;
        itr++;   
    }

    vec.size();                 //向量大小
    vec.clear();                //清空

    return 0;  
}  

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

輸出Vector的中的元素
vector”float” vecClass;
int nSize = vecClass.size();

https://www.cnblogs.com/90zeng/p/Vector_erase.html
http://blog.csdn.net/duan19920101/article/details/50617190

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章