簡體   English   中英

在沒有c ++ 11的情況下,刪除地圖最后插入的元素的正確方法是什么?

[英]What is the correct way to erase the last inserted element of a map without c++11?

這個問題是不言而喻的。 但補充一下,假設: map<int,int>至少包含10個插入的元素。 刪除最后插入的元素的正確方法是什么?

我所插入的最后一個元素不是地圖的最后一個元素,而是最后一次插入元素時插入的元素。

將迭代器保存到最后插入的元素。 映射中的元素按鍵值而不是插入順序排序。

map::insert將迭代器返回到最后插入的元素(以及指示是否發生插入的bool值)。

auto p = yourMap.insert(k,v);
if(p.second) {
    lastInsert = p.first;
} else {
    //Ambiguous. Depending on what you want
    //this could be an error, or you update the value and the iterator,
    //or you update just the value.
}

http://en.cppreference.com/w/cpp/container/map/insert

沒有用於執行此操作的API函數。 如果跟蹤插入元素的順序很重要,那么您將必須具有插入的vector<map<...>::iterator> ,並在插入時保持最新您從map刪除了東西。

具體執行方式取決於代碼的結構, map位置以及管理與其交互的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM