Answer the question
In order to leave comments, you need to log in
How does std::list work?
How is a container implemented std::list
in 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."
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
myList.emplace(it, 5, "Value"); // То это должно быть очень быстро
O(n)
Answer the question
In order to leave comments, you need to log in
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::vector
via []
or method at(index)
.
In std::list
order 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 questionAsk a Question
731 491 924 answers to any question