在没有c ++ 11的情况下擦除地图的最后插入元素的正确方法是什么?

Vin*_*rta 1 c++ map

问题是不言自明的.但补充假设:map<int,int>至少插入10个元素.删除最后插入的元素的正确方法是什么?

插入的最后一个元素我的意思是,不是地图的最后一个元素,而是我最后一次插入元素时插入的元素.

Cub*_*bic 6

将迭代器保存到最后插入的元素.地图中的元素按键值排序,而不是按插入顺序排序.

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.
}
Run Code Online (Sandbox Code Playgroud)

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


Nic*_*las 5

这样做没有API函数.如果跟踪您插入元素的顺序很重要,那么您将不得不进行vector<map<...>::iterator>插入,并在从中删除内容时保持最新map.

具体取决于您的代码的结构,位置map以及与之交互的内容.