c++11移动std::deque或std::list的插入

c++11 move insertion for std::deque or std::list

本文关键字:std 插入 list deque 移动 c++11      更新时间:2023-10-16

我相当了解右值引用是如何工作的,但我不太确定它们是如何与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()));

这将适用于listdeque,但语义不同。插入到新列表将需要分配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())
);