我似乎无法弄清楚并尝试了以下建议:
Move `unique_ptr`s between sets
how to move an std::unique_ptr<> from one STL container to another?
我有两个包含唯一指针的集合:
std::set<std::unique_ptr<some_type>> s1, s2;
指针当然是唯一的,但 some_type 的值可能是也可能不是,所以在将 s2 连接到 s1 之后,s1 的大小可能与 |s1 + s2| 相同或一样大。
看来我应该能够做到这一点:
move(s2.begin(), s2.end(), inserter(s1, s1.end()));
但这在 clang++ 3.8/g++ 5.4 中失败了。
这里缺少什么?
最佳答案
它不起作用,因为 std::set
只给出 const
访问其元素。无法从 std::set
中移出某些内容.参见 Is it possible to move an item out of a std::set?
在 C++14 中没有好的方法可以做到这一点,但在 C++17 中有一个 merge
为此目的提供的方法,它只是重新排列数据结构的内部指针,而不复制或移动任何元素:
s1.merge(s2);
C++14 中一个比较合理的解决方法是更改 std::set<std::unique_ptr<T>>
至 std::map<T*, std::unique_ptr<T>>
.然后你可以这样做:
while (!s1.empty()) {
s2[s1.begin()->first] = std::move(s1.begin()->second);
s1.erase(s1.begin());
}
关于c++ - 将 unique_ptr 从一个集合移动到另一个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186630/