将键移出 std::map<>&& [英] Moving keys out of std::map<> &&
问题描述
我想让我们说 getKeys()
函数从 map
中获取不可复制的键:
I'd like to have let's say getKeys()
function getting not-copiable keys out of a map
:
class MyObj {
// ... complex, abstract class...
};
struct Comparator { bool operator()(std::unique_ptr<MyObj> const &a, std::unique_ptr<MyObj> const &b); };
std::vector<std::unique_ptr<MyObj>> getKeys(std::map<std::unique_ptr<MyObj>, int, Comparator> &&map) {
std::vector<std::unique_ptr<MyObj>> res;
for (auto &it : map) {
res.push_back(std::move(it.first));
}
return res;
}
但是它不起作用,因为it
(.first
) 中的键是const
.任何提示如何解决它?注意:在我们的环境中,我不允许使用 C++17 函数 std::map::extract()
.
But it is not working because the key in it
(.first
) is const
. Any tips how to solve it? Note: In our environment I'm not allowed to use C++17 function std::map::extract()
.
是否可以使用 const_cast
因为 map
无论如何都会被破坏?
Is it somehow ok to use const_cast
because map
will be destructed anyway?
res.push_back(std::move(const_cast<std::unique_ptr<MyObj> &>(it.first)));
我想避免克隆 MyObj
.
我知道为什么不能修改 std::map
容器的键,但是对于在键修改后立即销毁的映射仍然不允许吗?
I know why keys of a std::map
container cannot be modified but is it still disallowed for a map that is going to be destructed immediately after the key modification?
推荐答案
注意:在我们的环境中,我不允许使用 C++17 函数
std::map::extract()
.
耻辱 - 它是为了解决这个问题而引入的.
Shame - it was introduced to solve this problem.
是否可以使用 const_cast
因为地图无论如何都会被破坏?
Is it somehow ok to use
const_cast
because map will be destructed anyway?
没有
我想避免克隆 MyObj
.
对不起;您至少需要克隆密钥.
Sorry; you'll need to clone the keys at least.
我知道为什么不能修改 std::map
容器的键,但是对于在键修改后立即销毁的映射仍然不允许吗?
I know why keys of a
std::map
container cannot be modified but is it still disallowed for a map that is going to be destructed immediately after the key modification?
是的.
地图的内部机制无法知道它的命运在等待.
The map's internal machinery has no way of knowing that its destiny awaits.
这篇关于将键移出 std::map<>&&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!