• <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 閱讀(357) 評論(0)  編輯 收藏 引用 所屬分類: C/C++

            導航

            隨筆分類

            隨筆檔案

            最新評論

            精品无码久久久久久国产| 狠狠精品干练久久久无码中文字幕| 亚洲欧美成人久久综合中文网 | 久久免费高清视频| 成人午夜精品久久久久久久小说| 久久精品国产一区二区| 综合久久国产九一剧情麻豆| 国产亚洲美女精品久久久| 一本久久知道综合久久| Xx性欧美肥妇精品久久久久久| 欧美亚洲国产精品久久| 国产69精品久久久久99| 狠狠色丁香久久婷婷综合五月| 日本亚洲色大成网站WWW久久| 久久精品国产亚洲AV高清热 | 狠狠色丁香婷婷综合久久来| 久久亚洲AV成人无码软件| 91精品国产综合久久香蕉| 97r久久精品国产99国产精| 久久精品国产99久久久古代| 久久99国产一区二区三区| 久久r热这里有精品视频| 国产人久久人人人人爽| 99精品国产99久久久久久97| 日本精品久久久久影院日本| 久久九九久精品国产| 久久精品99无色码中文字幕| 久久99国产精品久久99| 久久99国内精品自在现线| 亚洲AV日韩精品久久久久| 亚洲综合久久夜AV | 久久人人爽人人爽人人片AV麻烦| 婷婷久久综合九色综合九七| 欧美激情精品久久久久久久九九九 | 久久国产亚洲精品无码| 久久婷婷成人综合色综合| 五月丁香综合激情六月久久| 亚洲精品蜜桃久久久久久| 亚洲AV无码久久| 精品久久久久久综合日本| 久久国产精品-久久精品|