c++ - 为什么我不能 move map 的元素?

标签 c++ dictionary key constants move

我希望能够更改 map 元素的键。

我认为处理该问题的一个好方法是从 map move 元素,如下所示:

map<char, int> foo{{'a', 1}, {'b', 2}, {'c', 3}};

foo['z'] = move(*foo.find('c')).second;

for(auto& i: foo){
    cout << i.first << ' ' << i.second << endl;
}

这个输出:

a 1
b 2
c 3
z 3

而不是我希望的:

a 1
b 2
z 3

有什么方法可以实现吗?

最佳答案

首先,move不 move 任何东西;它只是将它的参数转换成一个右值,这样其他东西就可以从它 move 。其次,从一个对象中移出并不会破坏它,或者将它从容器中移除,它只是让它处于有效的、未指定的状态。最后,“move ”一个像 pair<const char, int> 这样的简单类型只包括复制它(特别是因为 const 意味着您无论如何都不能修改 key ,如果您强制更改它会破坏 map )。

所以单独的 move 什么都不做,你的代码等同于

foo['z'] = foo.find('c')->second;

它只是添加一个新元素,其中包含相同映射值的拷贝。

您可以将映射值 move 到新元素,然后删除旧元素。

auto found = foo.find('c');
if (found != foo.end()) {
    foo['z'] = move(found->second);
    foo.erase(found);
}

关于c++ - 为什么我不能 move map 的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28501045/

相关文章:

c++ - 使用 fstream 库并在屏幕上打印时出现文件问题?

c++ - 如何在线程退出时触发代码,而不使用函数 *_at_thread_exit?

python - 以更快/更好的方式从列表中查找具有最接近值的字典

dictionary - Racket : (map #(procedure) (list)) 中的 Clojure 等效项

android - map 的 Android 键类似于 youtube 键吗?

python - 停止嵌入式 python

c++ - 如何制作一个大小为变量的数组?

key - NCurses 和 ESC、ALT 键

c++ - 二叉堆与二叉树 C++

json - 如何使用jq对对象进行展平的逆操作?