which is faster list or vector?

Started by
2 comments, last by Sneftel 13 years, 9 months ago
im writing a program , i need to able to add to the top of the list and be able to remove any of the items no matter were it is in the list , apart from list and vector is there another way of doing it NOT ARRAYS because it wont work , please.

and out of the 2 , list and vector , which would be faster to use
Advertisement
a std::vector is basically an array. If you were to remove from the middle, the array would be shifted around and shrunk. A list, if you were to remove from the middle, would not need to copy data to shrink an array. Rather, it would join the next and previous nodes in the linked list.

If you are going to be removing things a lot, use a list. If you are going to be accessing things a lot without removing, use a vector.
------------Anything prior to 9am should be illegal.
Also, if the order is not very important, you can remove quickly from a vector by moving the last element into the position you want to remove. But perhaps this is not an option for you.

The only way to really know which way is faster is to implement both and measure.

Vectors also have the advantage of constant-time random access; that is, you can do myvec[7], but not mylist[7]. Additionally, they are much more cache- and allocator-friendly, which mitigates many of the advantages of list. Removing an element from the middle of a vector<int> is often faster than removing an element from the middle of a list<int>, for sizes up to hundreds of elements.

Bottom line: If you don't have a strong preference, use vector or deque, and switch to list if and when you have a good reason.

This topic is closed to new replies.

Advertisement