C++ STL 練手(vector的使用)

  1. vector的使用
  2. list的使用
  3. deque的使用
  4. set的使用
  5. map的使用
  6. multiset的使用
  7. multimap的使用
#include <vector>  
#include <iostream>  
#include <algorithm>  
#include <stdexcept>  
using namespace std;

void print(int num)
{
    cout << num << " ";
}

int main()
{
    //1. 初始化  
    vector<int> v;
    vector<int>::iterator iv;

    v.reserve(100);//設(shè)置vector最小的元素容納數(shù)量  
    v.assign(10, 2);//將10個(gè)值為2的元素賦到vector中  
    cout << v.capacity() << endl; //返回vector所能容納的元素?cái)?shù)量(在不重新分配內(nèi)存的情況下)  
    cout << v.size() << endl; //返回Vector實(shí)際含有的元素?cái)?shù)量  
    cout << endl;

    //2. 添加  
    //注意:push_front()只適用于list和deque容器類型  
    for (int i = 0; i < 10; i++)
        v.push_back(i);
    for_each(v.begin(), v.end(), print);//需要#include <algorithm>  
    cout << endl;
    cout << v.size() << endl;
    cout << endl;

    //3. 插入及遍歷、逆遍歷  
    v.insert(v.begin() + 3, 99);
    v.insert(v.end() - 3, 99);
    for_each(v.begin(), v.end(), print);
    cout << endl;
    for_each(v.rbegin(), v.rend(), print);//在逆序迭代器上做++運(yùn)算將指向容器中的前一個(gè)元素  
    cout << endl;

    //一般遍歷寫法  
    for (iv = v.begin(); iv != v.end(); ++iv)
        cout << *iv << " ";
    cout << endl;
    cout << endl;

    //4. 刪除  
    v.erase(v.begin() + 3);
    for_each(v.begin(), v.end(), print);
    cout << endl;
    v.insert(v.begin() + 3, 99);//還原  

    v.erase(v.begin(), v.begin() + 3); //注意刪除了3個(gè)元素而不是4個(gè)  
    for_each(v.begin(), v.end(), print);
    cout << endl;

    //注意:pop_front()只適用于list和deque容器類型  
    v.pop_back();
    for_each(v.begin(), v.end(), print);
    cout << endl;
    cout << endl;

    //5. 查詢  
    cout << v.front() << endl;
    cout << v.back() << endl;

    //危險(xiǎn)的做法,但一般我們就像訪問數(shù)組那樣操作就行  
    //for (int i = 15; i < 25; i++)
        //cout << "Element " << i << " is " << v[i] << endl;
    //安全的做法  
    int i;
    try
    {
        for (i = 15; i < 25; i++)
            cout << "Element " << i << " is " << v.at(i) << endl;
    }
    catch (out_of_range err)//#include <stdexcept>  
    {
        cout << "out_of_range at " << i << endl;
    }
    cout << endl;

    //6. 清空  
    v.clear();
    cout << v.size() << endl;//0  
    for_each(v.begin(), v.end(), print); //已經(jīng)clear,v.begin()==v.end(),不會(huì)有任何結(jié)果。  

    return 0;
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容