c++ - std::move(key) 在迭代 unordered_map<string, string> 时?

标签 c++ c++11 unordered-map

以下安全吗?

unordered_map<string, string> my_map;
unordered_map<string, double> new_map;
for(auto&& [key, value] : my_map) {
    new_map.insert({std::move(key), std::stod(value)});
}

我在循环后没有使用 my_map,在迭代时可以从 key 移动吗?

最佳答案

是和否。

不,因为它没有达到您的预期。 unordered_map 的键是 const 限定的。它无法被移动。

是的,因为代码是安全的并且可以编译。 key 只需复制即可。

这对于所有有序和无序关联容器都是相同的,包括 mapsetunordered_multiset 等。

关于c++ - std::move(key) 在迭代 unordered_map<string, string> 时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069004/

相关文章:

c++ - 堆问题

C++数据结构错误输出(链表)

c++ - 在 C++ 程序中处理 "system"调用的结果

multithreading - 将异常抛出到另一个线程

c++ - 为什么 `using`关键字不能用于静态类成员?

c++ - std::unordered_map 内部使用哈希吗?

c++ - C/C++中的内存分配

c++ - 限定符丢失转换 C++

c++ - 如何在带有来自 std::string 的 unordered_map 的字符串文字上使用 is_transparent 功能?

c++ - 你什么时候使用 std::unordered_map::emplace_hint?