c++ - 将 unique_ptr 从一个集合移动到另一个集合

标签 c++ c++11 stl

我似乎无法弄清楚并尝试了以下建议:

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/

相关文章:

c++ - 如何获取指向 Factory::method(variadics ...) 的指针以进行延迟调用?

c++ - 如何将 peek 函数添加到我的堆类中?

c++ - 有没有一种 STL 方法可以首先验证(文本)文件是只读的?

c++ accumulate如何将特定函数应用于最后一个元素

c++ - STL 和 vector 是否提供排序选项?

move 操作后 C++ lambda ‘this’ 指针失效

c++ - 有没有办法在 GCC 中禁用内联汇编程序?

c++ - 如何编写启用 ADL 的尾随返回类型或 noexcept 规范?

c++ - 检测单元测试中的特定函数调用

c++ - std::complex<T> 的显式模板特化