1. 程式人生 > >當C++容器的迭代器iterator遇到刪除函式erase時

當C++容器的迭代器iterator遇到刪除函式erase時

      C++中添加了各種各樣的STL容器,不僅數量眾多,而且功能強大,如果能夠正常使用,可以使我們省去諸多時間。迭代器(iterator)是一種物件,它能夠用來遍歷標準模板庫容器中的部分或全部元素,每個迭代器物件代表容器中的確定的地址,簡單點就是每個“節點”物件的“指標”。

       不過,雖然C++的STL容器功能強大,但是由於C++語言的自由性(簡直自由的令人髮指),也會讓我們在使用中遇到很多麻煩。最近就遇到了一個問題:在使用容器時,有時需要對迭代器指向的物件進行erase操作,如果只簡單進行了刪除操作,並且下面依然要用到迭代器,那麼就有可能出現一些問題。

        對於關聯容器,如map,set(以及multi型別)等,erase當前的迭代器iterator,僅僅會使當前的iterator失效,並不影響以後的內容,所以只要在進行刪除前,預先保留下一個當前迭代器的遞增值即可。這是因為關聯類容器使用了紅黑樹實現,刪除一個節點不會對其他節點造成影響。

    std::set<int> myset = {1, 2, 3, 4, 5, 6};
    std::set<int>::iterator it = myset.begin();
    for (; it != myset.end() ;) {
        if (*it == 3) {
            myset.erase(it++);
        } else {
          ++it;  
        }
    }
        上面erase的引數是當前迭代器的一個副本(右++的性質),it本身已經指向下一個有效的迭代器。

        對於序列式容器,如 vector,deque等,刪除當前節點會使後面的所有節點的迭代器失效。這是因為這類容器每次進行插入或者刪除都會使之後的元素位置進行重新移動定位,致使之前的迭代器失效。但是erase函式卻會有返回值:

A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.

erase函式會返回指向下一節點的有效迭代器,所以

    std::vector<int> myvec = {1, 2, 3, 4, 5, 6};
    std::vector<int>::iterator it = myvec.begin();
    for (; it != myvec.end() ;) {
        if (*it == 3) {
            it = myvec.erase(it);
        } else {
          ++it;  
        }
    }

上面的關聯容器的erase函式雖然也會有返回值,但是隻針對引數為key值,並且返回值為個數:

   void erase ( iterator position );
size_type erase ( const key_type& x );
     void erase ( iterator first, iterator last );

Only for the second version, the function returns the number of elements erased, which in map containers is 1 if an element with a key value of x existed (and thus was subsequently erased), and zero otherwise.

        最後就是常用的list,自己使用時發現上面兩種方法均可以實現,在手冊中給出了erase函式的返回值:只想下一個有效節點的雙向迭代器

A bidirectional iterator pointing to the new location of the element that followed the last element erased by the function call, which is the list end if the operation erased the last element in the sequence.