C++.stl map::erase陷阱

來源:互聯網
上載者:User

標籤:

map::erase函數在不同版本stl中的差異 1. C++98和C++11標準

http://www.cplusplus.com/reference/map/map/erase/

 

2. pj stl(windows)

       map::erase函數的windows實現版本(C++11標準)會返回一個map::iterator:

iterator  map::erase(const_iterator _Where);iterator  map::erase(const_iterator _First, const_iterator _Last);size_type map::erase(const key_type& _Keyval);
3. sgi stl(linux)

       map::erase函數的linux實現版本(C++98標準)會返回一個void:

void      map::erase(iterator __position);void      map::erase(iterator __first, iterator __last);size_type map::erase(const key_type& __x);
 map::erase函數的正確使用方式

       map::erase函數的正確使用方式:

typedef std::map<int, int>           KG_TestMap;typedef std::map<int, int>::iterator KG_TestMapIter;std::map<int, int> mapTest;for (KG_TestMapIter iter = mapTest.begin(); iter != mapTest.end();){    mapTest.erase(iter++);}

       這種方法利用了後++的特性,執行mapTest.erase(iter++)語句分成了兩個過程:
       • 後++操作將為當前iter儲存一個副本tmp,然後遞增當前iter指向下一個元素,最後返回該副本tmp

       • 調用map::erase函數,tmp所指向的元素。

// code in pj stl_Myiter operator++(int){ // postincrement    _Myiter _Tmp = *this;    ++*this;    return (_Tmp);}

// code in sgi stl
_Self operator++(int)
{
_Self __tmp = *this;
    _M_increment();
    return __tmp;
}

 

C++.stl map::erase陷阱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.