J
J
Junior0072016-09-20 17:33:36
C++ / C#
Junior007, 2016-09-20 17:33:36

How does std::list work?

How is a container implemented std::listin C++?
Specifically, I can't understand these lines:
1) "A list is a container that supports fast insertion and removal of elements from any position in the container.

Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions."

2) "Fast random access is not supported.
The main drawback of lists and forward_lists compared to these other sequence containers is that they lack direct access to the elements by their position

Any position and random access are not the same?
Based on the first statement, if I write:
myList.emplace(it, 5, "Value"); // То это должно быть очень быстро

And judging by the second, such a record should work forO(n)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fat Lorrie, 2016-09-20
@Junior007

Random access is index access, with constant complexity ( O(1)), when the offset is calculated and we can immediately jump to the desired element, as in std::vectorvia []or method at(index).
In std::listorder to get (insert, delete, etc.) somewhere in the middle, we must get to this place, passing all the elements below (above) along the way, one after the other. This is quite slow ( O(n)). But the insert itself will be cheap anywhere ( O(1)).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question