实现forward_list后的剪接
Splice_after implementation of forward_list
在forward_list
中有一个函数splice_after
(供参考),特别是给定链接中的函数#3。考虑到list
是单独连接的,如何实现呢。
作为练习,当我实现它时,我必须迭代列表,直到我到达first
之前的节点(这样我就可以将first
连接到last
),然后再次迭代,直到我达到last
之前的节点为止(这样我可以将当前列表的节点连接到last
之前的节点)。这对我来说似乎并不高效,我想知道是否有更好的方法可以在不迭代的情况下做到这一点?
我怀疑您误读了有点微妙的范围规范,该规范说"(first,last)"被移动,而不是"[first,last)"(注意左括号/括号)。也就是说,正如名称所示,拼接操作只在第一个对象之后开始。
该函数的实现实际上非常简单(如果忽略迭代器的常量以及它可能需要处理不同分配器的事实):
void splice_after(const_iterator pos, forward_list& other,
const_iterator first, const_iterator last) {
node* f = first._Node->_Next;
node* p = f;
while (p->_Next != last._Node) { // last is not included: find its predecessor
p = p->_Next;
}
first._Node->Next = last._Node; // remove nodes from this
p->_Next = pos._Node->_Next; // hook the tail of the other list onto last
pos._Node->_Next = f; // hook the spliced elements onto pos
}
此操作具有线性复杂性,因为它需要找到last
的前一个。
(社区维基,请投稿)
A -> B -> C -> D -> E
^
^ pos points to C
在other
列表中
U -> V -> W -> X -> Y -> Z
^ ^
^ first ^ last
呼叫.splice(pos, other, first, last)
我们要把W和X排到最前面。即first
和last
之间但不包括的所有内容。最终A->B->C->W->X->D->E
位于顶部,U->V->Y->Z
位于底部。
auto copy_of_first_next = first->next;
first->next = last;
// the `other` list has now been emptied
auto copy_of_pos_next = pos->next;
pos -> next = first;
while(first->next != last) ++first;
// `first` now points just before `last`
first->next = copy_of_pos_next
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- C++中带有List类的迭代器Segfault
- 使用"std::unordereded_map"映射到"std::list"对象
- GCC对可能有效的代码抛出init list生存期警告
- 使用std::list创建循环链表
- 重载Singly Linked List中的赋值运算符
- 完美前进使用 std::forward vs RefRefCast
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- "std::list::splice(std::const_iterator pos, std::list&& other)"是否保证将"其他"留空?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- QStringList vs list<shared_ptr<QString>> 性能比较C++
- 包含 std::list 的结构体的 C++ 初始化
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- 在基于范围的 for 循环期间插入 std::list 的后面
- 循环挂起迭代的 std::擦除 on std::list