gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:19:33 29 4
gpt4 key购买 nike

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

我指的是最后插入的元素,不是 map 的最后一个元素,而是我上次插入元素时插入的元素。

最佳答案

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

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

关于c++ - 在没有 c++11 的情况下删除 map 最后插入的元素的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12121188/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com