美文网首页
STL迭代器失效

STL迭代器失效

作者: 钟离惜 | 来源:发表于2020-08-31 22:44 被阅读0次

    迭代器在移除元素时迭代器可能失效。
    vector如果开辟新的内存时迭代器可能失效。
    新增元素时尾迭代器可能失效。
    ......

    #include <iostream>
    #include <vector>
    #include <list>
    #include <deque>
    #include <map>
    #include <set>
    using namespace std;
    
    int main()
    {
        {
            vector<int> vec;
            vec.push_back(1);
            vec.push_back(2);
            vector<int>::iterator ite = vec.begin();
            cout << "vec:" << *ite << endl;
            ite = vec.erase(ite);
            //vec.erase(ite);
            cout << "vec:" << *ite << endl;
        }
        cout << endl;
        {
            list<int> List;
            List.push_back(1);
            List.push_back(2);
            list<int>::iterator ite = List.begin();
            cout << "List:" << *ite << endl;
            ite = List.erase(ite);
            //List.erase(ite);
            cout << "List:" << *ite << endl;
        }
        cout << endl;
        {
            deque<int> Deque;
            Deque.push_back(1);
            Deque.push_back(2);
            deque<int>::iterator ite = Deque.begin();
            cout << "Deque:" << *ite << endl;
            ite = Deque.erase(ite);
            //Deque.erase(ite);
            cout << "Deque:" << *ite << endl;
        }
        cout << endl;
        {
            map<int, int> nnmap;
            nnmap.insert(map<int, int>::value_type(1, 1));
            nnmap.insert(map<int, int>::value_type(2, 2));
            map<int, int>::iterator ite = nnmap.begin();
            cout << "nnmap:" << ite->first << endl;
            ite = nnmap.erase(ite);
            //nnmap.erase(ite);
            cout << "nnmap:" << ite->first << endl;
        }
        cout << endl;
        {
            set<int> Set;
            Set.insert(1);
            Set.insert(2);
            set<int>::iterator ite = Set.begin();
            cout << "Set:" << *ite << endl;
            ite = Set.erase(ite);
            //Set.erase(ite);
            cout << "Set:" << *ite << endl;
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:STL迭代器失效

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