我希望有一个名为
但是它没有起作用,因为
是否可以使用
getKeys()
的函数,可以从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()
。是否可以使用
const_cast
,因为 map
将被销毁?res.push_back(std::move(const_cast<std::unique_ptr<MyObj> &>(it.first)));
我希望避免克隆MyObj
。
我知道为什么std::map
容器的键不能被修改,但如果这个map在键被修改后立即被销毁,是否仍然不允许修改键?
std::unique_ptr
切换到std::shared_ptr
吗? - Daniel Langr