The question is not why std::vector does not offer an operation, but why std::list offers it. The STL design is focused on the separation of containers and algorithms using iterators, and in all cases when the algorithm can be effectively implemented from the point of view of iterators, that is, an option.
However, there are cases when there are specific operations that can be implemented much more efficiently with knowledge of the container. This is a case of removing items from a container. The cost of using the delete-erase idiom is linear in size of the container (which cannot be significantly reduced), but this hides the fact that in the worst case, all but one operation are copies of objects (the only element is that the match is the first), and these copies can be quite a significant hidden cost.
Performing the operation as a method in std::list , the complexity of the operation will still be linear, but the cost associated with it for each of the deleted elements is very small, several copies of the pointer and the release of node in memory. At the same time, implementation as part of a list can provide more reliable guarantees: pointers, links, and iterators to elements that are not erased, do not become invalid in the operation.
Another example of an algorithm that is implemented in a specific container is std::list::sort , which uses mergesort , which is less efficient than std::sort , but does not require random access iterators.
Thus, algorithms are implemented as free functions using iterators, if there are no good reasons for providing a specific implementation in a specific container.
David Rodríguez - dribeas
source share