std::vector removing a random element

V

vsgdp

From what I learned, if you want to do random element insertions and
deletions you should use a list. But, with std::vector, if the order of the
elements does not matter, couldn't you efficiently remove a random element
by swapping it with the last element and then just using pop_back? Does
erase do this internally? Or does erase do the element shift to fill in the
gap?
 
J

John Carson

vsgdp said:
From what I learned, if you want to do random element insertions and
deletions you should use a list.

A list inserts/deletes equally well in the middle of a list as at either end
whereas a vector inserts/deletes more quickly at the end than it does in the
middle. This doesn't actually tell you anything about the relative
efficiency of lists and vectors for middle operations; it only compares list
operations to other list operations and vector operations to other vector
operations. If relative efficiency of lists and vectors is important, you
should time them for the actual container sizes and operations that are
relevant to you.
But, with std::vector, if the order
of the elements does not matter, couldn't you efficiently remove a
random element by swapping it with the last element and then just
using pop_back?

Yes. For large vectors, a swap and pop_back operation would be quicker. Much
of the time, however, preserving the order of elements does matter.
Does erase do this internally? Or does erase do the
element shift to fill in the gap?

erase preserves the order of remaining elements, so it shifts elements.
 
A

Alipha

vsgdp said:
From what I learned, if you want to do random element insertions and
deletions you should use a list. But, with std::vector, if the order of the
elements does not matter, couldn't you efficiently remove a random element
by swapping it with the last element and then just using pop_back? Does
erase do this internally? Or does erase do the element shift to fill in the
gap?

What operations are you doing with this collection of objects? By
random, do you mean, randomly selected or random access? If you mean
random access, and if the sequence order of the elements does not
matter, it sounds like you should be using a std::set or std::multiset.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top