问题描述
我想使用 std :: forward_list
因为:
转发列表是一个支持快速插入和删除元素的容器容器
Forward list is a container which supports fast insertion and removal of elements from anywhere from the container
但没有* std :: forward_list :: push_back *实现。
But there's no *std::forward_list::push_back* implementation.
有没有高性能的方法来添加支持的一个或没有理由这样做?
Is there a high-performance way to add support for the one or no reason to do it?
推荐答案
code> std :: forward_list 支持快速插入和删除,但不会遍历到结尾。要实现 .push_back
,你首先需要到列表的末尾,这是O(N),并不快,这可能是为什么它不是实施。
std::forward_list
supports fast insertion and removal, but not traversal to the end. To implement .push_back
, you'll first need to get to the end of the list, which is O(N) and not fast at all, which is probably why it's not implemented.
您可以通过增加来找到最后一个元素的迭代器。 before_begin
N次
auto before_end = slist.before_begin();
for (auto& _ : slist)
++ before_end;
,然后使用 .insert_after
或 .emplace_after
以插入元素:
and then use .insert_after
or .emplace_after
to insert the element:
slist.insert_after(before_end, 1234);