c++11移动std::deque或std::list的插入
c++11 move insertion for std::deque or std::list
我相当了解右值引用是如何工作的,但我不太确定它们是如何与STL中的迭代器一起工作的。这是我想要的东西:
void insertList(std::list<int>& L, std::list<int>&& R, std::list<int>::iterator insertPoint)
{
L.insert(insertPoint, R.begin(), R.end()); // want to use move semantics
}
现在我知道std::list有一个拼接方法。但我想知道这是否可行。这对德克也有用吗?
splice
和移动容器内容是不同的操作。在splice
的情况下(这不能用deque
完成),整个节点从一个容器转移到另一个容器。节点将不再位于原始容器中,操作也不会执行任何分配。
使用与您所述算法类似的算法移动内容的替代方法,但使用移动迭代器:
L.insert(insertPoint,
std::make_move_iterator(R.begin()),
std::make_move_iterator(R.end()));
这将适用于list
和deque
,但语义不同。插入到新列表将需要分配std::distance(R.begin(),R.end())
节点,其中的内容将通过从原始容器移动来填充。这降低了创建新节点的成本,但仍然需要对它们进行分配。请注意,旧列表仍将包含所有节点,尽管随着数据内容的移动,这些节点将为空。
在std::list
的情况下,您应该更喜欢splice
,但这在其他容器上不可用。对于其他容器,您将使用上述方法,其中必须考虑构建容器数据结构的成本,尽管可以避免创建存储数据的成本。
您想要std::make_move_iterator()
:
L.insert(
insertPoint,
std::make_move_iterator(R.begin()),
std::make_move_iterator(R.end())
);
相关文章:
- 有效地使用std::unordered_map来插入或增加键的值
- 将重物插入std::map
- 如何有效地在 std::vector 中插入一对?
- 在基于范围的 for 循环期间插入 std::list 的后面
- 为 std::vector 编写自定义插入函数
- std::unordered_map 如果输入大小已知,如何优化批量插入
- C++ - 最坏情况和平均情况插入时间复杂度在 std::unordered_map <int,int>?
- 找不到最新插入到 std::map 中的键
- 在 std::map 中插入数组元素
- 有没有更快的方法可以在 std::vector 中插入元素
- 插入 std::set 作为 std::map 的键
- 通过构造函数插入 std::map
- 将带有模板的自定义类插入到 std::map 中
- 如何将 n 个连续元素插入到元素类型不可复制的 std::vector 中?
- 将唯一指针插入std::映射
- 如果迭代器没有因插入而无效,则使用std::find和C::insert()是线程安全的
- std::为插入和排序设置不同的比较器
- std::映射导致插入时出现C2664错误
- 为什么std ::插入需要复制构造性
- std::插入无序集合(或映射)的迭代器