美文网首页
C++ STL 练手(deque的使用)

C++ STL 练手(deque的使用)

作者: 863cda997e42 | 来源:发表于2018-02-12 15:45 被阅读20次
    1. vector的使用
    2. list的使用
    3. deque的使用
    4. set的使用
    5. map的使用
    6. multiset的使用
    7. multimap的使用
    #include <deque>  
    #include <iostream>  
    #include <algorithm>  
    #include <stdexcept>  
    using namespace std;  
      
    void print(int num)  
    {  
        cout << num << " ";  
    }  
      
    int main()  
    {  
        //1. 初始化  
        deque<int> v;  
        deque<int>::iterator iv;  
      
        v.assign(10, 2);//将10个值为2的元素赋到deque中  
        cout << v.size() << endl; //返回deque实际含有的元素数量  
        cout << endl;  
      
        //2. 添加  
        v.push_front(666);  
        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);//在逆序迭代器上做++运算将指向容器中的前一个元素  
        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个元素而不是4个  
        for_each(v.begin(), v.end(), print);  
        cout << endl;  
      
        v.pop_front();  
        v.pop_back();  
        for_each(v.begin(), v.end(), print);  
        cout << endl;  
        cout << endl;  
      
        //5. 查询  
        cout << v.front() << endl;  
        cout << v.back() << endl;  
      
        //危险的做法,但一般我们就像访问数组那样操作就行  
        //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); //已经clear,v.begin()==v.end(),不会有任何结果。  
      
        return 0;  
    }  
    
    ```

    相关文章

      网友评论

          本文标题:C++ STL 练手(deque的使用)

          本文链接:https://www.haomeiwen.com/subject/zsartftx.html