I have a 'list' of objects, from which I want to take object at random position and push it on front of this list. Only this kind of operation will be performed. So I don't need a fast access to end of the list, only to it's front and average access to any other place.
Which container would be the best for this? I was thinking about std::vector
, but I've read that insert
operation is not efficient. Then I came up with std::deque
because of it's fast access to front, but what about efficiency of it's erase
at specific position method?
Thanks in advance for help.
We can give you guidelines, but no definitive answer – you need to benchmark that yourself because it crucially depends on your collection and object size:
std::vector
will be faster because even though you need to copy more data, the better random access time (O(1) vs O(n) for std::list
) and the cache locality will dominate.std::list
will be faster because although you need O(n) to pick a random object, insertion will be much faster since the copying of many large objects is very slow.But where exactly the cut-off between these two scenarios lies I cannot say.
Furthermore, if you can get away with swapping the elements instead of insertion, this is a no-brainer: always use a std::vector
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With