我有一个 std::map
对象。
std::map<std::string, std::string> m;
m.insert({ "abcd", "foo" });
m.insert({ "1234", "bar" });
我想获取并删除第一个元素,例如:
auto iter = m.begin();
auto [key, value] = std::move(*iter);
m.erase(iter);
do_something_with(key, value);
这被认为是安全的吗?
(从迭代器移动应该使键为空字符串,这使 m
成为无效映射。)
最佳答案
您可以使用 std::map::extract
像这样:
auto nh = m.extract(m.begin());
然后像这样使用键和值:
do_something(nh.key(), nh.mapped());
这具有不制作额外拷贝所需的属性。
关于c++ - 如何在没有额外拷贝的情况下从 std::map 安全地获取 "pop-front"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63276423/