简体   繁体   English

std :: list c ++是顺序的,然后如何在序列中的任何位置进行插入和擦除操作的恒定时间

[英]std::list c++ is sequential then how it can take constant time for insert and erase operations anywhere within the sequence

in c++ reference i read "Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions." 在c ++参考文献中我读到“列表是序列容器,它允许在序列中的任何地方进行恒定时间插入和擦除操作,并在两个方向上进行迭代。” my doubt is if it is sequential then how it can take constant time to delete and insert a node.Any way we have to traverse sequentially to reach that node . 我怀疑的是,如果它是顺序的,那么如何花费恒定的时间来删除和插入节点。任何方式我们必须顺序遍历以到达该节点。 Deleting node depends on its position 删除节点取决于其位置

O(1) referst to the complexity for inserting/erasing nodes provided you already have a handle (in the form of an iterator) to that node . O(1)指的是插入/擦除节点的复杂性,前提是您已经有一个句柄(以迭代器的形式)到该节点 Obtaining an iterator to the i th element of a list given an iterator to the first one is O(N). 给定第一个迭代器的列表的第i个元素的迭代器是O(N)。

This is quite often overlooked when judging the relative merits of std::list vs. say, std::vector . 在判断std::liststd::vector的相对优点时,经常会忽略这一点。 But note that both inserting and erasing elements return iterators that can be used for further insert/erase operations. 但请注意,插入和擦除元素都返回可用于进一步插入/擦除操作的迭代器。

Insertion before a given node (lets call it pos ) or as last node or deleting a given node is a constant time operation. 在给定节点之前插入(让我们称之为pos )或作为最后一个节点或删除给定节点是一个恒定时间操作。

std::list can be implemented as doubly linked list. std::list可以实现为双向链表。 Sequence containers should not be confused with contiguous memory requirement. 序列容器不应与连续的内存要求混淆。

Because the list is not sorted. 因为列表没有排序。 If you look closely, the actual function for putting elements in the list is list::insert(hint, element) ( http://www.cplusplus.com/reference/list/list/insert/ ). 如果仔细观察,将元素放入列表的实际函数是list::insert(hint, element)http://www.cplusplus.com/reference/list/list/insert/ )。 Ie for every insertion, the place where the element is added is already known, thus constant time. 即,对于每次插入,添加元素的位置是已知的,因此是恒定的时间。

Eg list::push_front(element) is short for insert(begin(), element) . 例如list::push_front(element)insert(begin(), element)缩写。

[That's mostly a comment, but it didn't fit in the margin] [这主要是一个评论,但它不符合边际]

Note that an std::list cannot be implemented as a single linked list to fulfill the complexity requirements: 请注意, 无法std::list实现为单个链表以满足复杂性要求:

  • Even when you already have an handle to a node of a single linked list, you cannot insert before it (resp. erase it) in constant time (since you would need access to the previous node). 即使您已经拥有单个链表的节点的句柄,也不能在常量时间之前插入(分别擦除它) (因为您需要访问前一个节点)。

That's why std::forward_list only provides insert_after and erase_after . 这就是为什么std::forward_list只提供insert_aftererase_after

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM