vector容器常用方法

來源:互聯網
上載者:User

標籤:迭代器   vector   

  • 容器簡介
    • 定義及初始化
    • 末尾插入元素
    • 遍曆 size 函數是可以動態增加的
    • 通過下標操作增加改變vector內容不是安全的操作
    • 僅能對已存在元素進行下標操作不存在會crash
    • 將元素一個容器複製給另外一個容器類型必須匹配容器類型和元素類型必須相同
  • 迭代器簡介
    • 定義
    • begin和end操作
    • 迭代器的自增和解引用操作
    • 迭代器的算術操作
    • const_iterator 唯讀

容器簡介定義及初始化
vector<int> vec(5,100);vector<string> strVec(10,"hello");
末尾插入元素
  vec.push_back(102);  strVec.push_back("what");
遍曆 size() 函數是可以動態增加的
    for(vector<int>::size_type ix=0;ix<vec.size(); ix++)    {         cout<<vec[ix]<<endl;        vec.push_back(ix+10);        cout<<"size is"<<vec.size()<<endl;        if(vec.size()==10)        {          break;        }    }    for(vector<string>::size_type jx=0;jx<strVec.size();jx++)    {         cout<<strVec[jx]<<endl;    }
通過下標操作增加改變vector內容,不是安全的操作
vector <int> vec2(10);    cout<<vec2[9]<<endl;    cout<<vec2[10]<<endl;
僅能對已存在元素進行下標操作,不存在會crash
vector<int> emptyVec;//cout<<emptyVec[0]<<endl;    error
將元素一個容器複製給另外一個容器,類型必須匹配,容器類型和元素類型必須相同
    vector<int> vecCopy(vec);    for(vector<int>::size_type i=0;i<vecCopy.size();i++)    {      cout<<vecCopy[i]<<endl;    }
迭代器簡介

所有標準庫容器都支援迭代器,但只有少數的容器支援下標操作

定義
    vector<int>::iterator iter;
begin和end操作

begin返回迭代器指向的第一個位置,end指向vector的末端元素的下一個

vector<string>::iterator iBegin=strVec.begin();vector<string>::iterator iEnd=strVec.end();
迭代器的自增和解引用操作

++iter指向第二個元素
*iter指向當前元素

    cout<<*iBegin<<endl;    cout<<*(iEnd-1)<<endl;     for(;iBegin<iEnd;iBegin++)    {      cout<<*iBegin<<endl;    }
迭代器的算術操作

iter+n iter-n
iter1-iter2

    string str("richard");    *(iBegin+3)=str;    cout<<*(iBegin+3)<<endl;        cout<<iEnd-iBegin<<endl;        vector<string>::iterator              mid=iBegin+strVec.size()/2;    cout<<*mid<<endl;
const_iterator 唯讀

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.