• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            GLORY | 學習·記錄

            coding for life

            危險的vector::erase

             1 #include<iostream>
             2 #include<vector>
             3 using namespace std;
             4 
             5 int main()
             6 {
             7     vector<int> a;
             8     a.push_back(1);
             9     a.push_back(2);
            10     a.push_back(3);
            11     a.push_back(4);
            12     a.push_back(5);
            13     
            14     vector<int>::iterator pos=a.begin()+2;
            15     vector<int>::iterator temp=pos+1;
            16     cout<<"temp now is"<<*temp<<endl;
            17     
            18     a.erase(pos);
            19     
            20     cout<<"temp now is"<<*temp<<endl;
            21     
            22     system("pause");
            23     return 0;
            24 }

            今天在用STL寫約瑟夫問題的時候,發現vector的行為總是產生詭異的結果,讓我百思不得其解。

            看上面代碼:
            一個vector里面有1到5,總共5個元素。把一個迭代器pos指向第三個元素3,另外一個temp指向第四個元素4,然后調用erase把第三個元素抹掉。
            注意,在這個時候繼續解引用temp的時候,會發現它指向的元素神奇的變成了5。

            問題就處在erase上面,在C++ Reference上面寫道:
            Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions, which may not be a method as efficient as erasing in other kinds of sequence containers (deque, list).

            This invalidates all iterator and references to elements after position or first.

            刪除vector一個元素,導致它后面的元素全部移動到新的位置,所以導致這個元素之后的所有迭代器都失效。


            在使用一個函數前應該對它的行為有清楚的了解。謹記。

            posted on 2011-03-11 15:41 meglory 閱讀(354) 評論(0)  編輯 收藏 引用 所屬分類: C/C++

            導航

            隨筆分類

            隨筆檔案

            最新評論

            国产成人久久激情91| 久久国产香蕉视频| 中文字幕热久久久久久久| 2020久久精品亚洲热综合一本| 色综合久久久久无码专区| 好属妞这里只有精品久久| 久久精品无码av| 97精品国产97久久久久久免费 | 国产成人综合久久综合| 色综合色天天久久婷婷基地| 久久亚洲国产精品成人AV秋霞| 久久精品人人做人人爽电影蜜月| 国产成人精品三上悠亚久久| 久久se精品一区二区| 久久久久av无码免费网| 亚洲国产日韩欧美综合久久| 99久久99久久精品国产片果冻| 久久久久久亚洲AV无码专区| 国产亚洲美女精品久久久| 久久精品无码一区二区三区日韩| 久久亚洲日韩精品一区二区三区| 7777精品久久久大香线蕉| 国产一区二区精品久久凹凸 | 色8久久人人97超碰香蕉987| 久久人妻少妇嫩草AV无码蜜桃| 久久精品二区| 久久婷婷国产麻豆91天堂| 欧美喷潮久久久XXXXx| 久久精品日日躁夜夜躁欧美| 久久有码中文字幕| 久久久久这里只有精品 | 日本高清无卡码一区二区久久| 国产99久久久国产精品~~牛| 国产精品免费久久久久影院| 国产精品美女久久久m| 久久精品国内一区二区三区 | 久久狠狠一本精品综合网| 久久精品国产只有精品2020| 久久亚洲高清观看| 91久久精品无码一区二区毛片| 久久91综合国产91久久精品|