Why is splicing an entire list or a range linear for std::forward_list?

梦想的初衷 提交于 2019-12-04 04:00:30

In the case of a forward_list, how would you make the range splice_after constant time? In the source list, you only have the iterators. To remove the nodes from the source forward linked list, you will need the node immediately before last, so you need to search the source linearly for that linked list node. Hence, why it's linear in the distance between first and last

The version that uses the entire source list still needs to search for the node immediately before the end of the source, so that it can be modified to point to the element after the splice in the destination. So it also requires linear time in the size of the source.

The range splice is the only reason that size wouldn't have been constant time in previous C++ standards. In fact the Sun CC compiler chose to make size constant time and all versions of splice linear.

Splicing an entire forward list is linear because you have to traverse the list you're merging to be able to link it's last node back into the list you're splicing into. I can't figure out why the range splice is linear though.

EDIT: As @Xeo points out, the range-based version also requires linear time because last is not included in the range and it needs to search from first to find the iterator before last.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!