Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector and list insertion

Could anybody know why inserting an element into the middle of a list is faster than inserting an element into the middle of a vector?

I prefer to use vector but am told to use list if I can. Anybody can explains why? And is it always recommended to use list over vector?

like image 801
user2310042 Avatar asked Apr 25 '26 00:04

user2310042


1 Answers

If I take the question verbatim, finding the middle of an array (std::vector) is a simple operation, you divide the length by two and then round up or down to get the index. Finding the middle of a doubly linked list (std::list) requires walking through all elements. Even if you know its size, you still need to walk over half of the elements. Therefore std::vector is faster than std::list, in other words one is O(1) while the other is O(n).

Inserting at a known position requires shuffing the adjacent elements for an array and just linking in another node for a doubly linked list, as others explained here. Therefore, std::list with O(1) is faster than std::vector with O(n).

Together, to insert in the exact middle, we have O(1) + O(n) for the array and O(n) + O(1) for the doubly linked list, making inserting in the middle O(n) for both container types. All this leaves out things like CPU caches and allocator speed though, it just compares the number of "simple" operations. In summary, you need to find out how you use the container. If you really insert/delete at random positions a lot, std::list might be better. If you only do so rarely and then only read the container, a std::vector might be better. If you only have ten elements, all the O(x) is probably worthless anyway and you should go with the one you like best.

like image 134
Ulrich Eckhardt Avatar answered Apr 26 '26 14:04

Ulrich Eckhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!