I’m looking for a std container like a std::list that can efficiently move an element to the front:
a-b-c-d-e
move “b” to front:
a-c-d-e-b
There is no such function in the std containers. Therefor, I think I must combine a remove and push_front function but has anyone can find a better idea?
Thank in advance.
If you don’t have to maintain the order of the other elements,
then the simplest solution is doubtlessly just to swap the
element you want with the first element in the container. This
will be efficient with all containers.
Otherwise,
std::listoffers aspliceoperation which couldbe used. Something like the following, I think:
This should end up with only a couple of pointer operations, and
no copies. On the other hand,
std::listcan be very slow ingeneral (because of its poor locality); I’d measure very
carefully against the naïve implementation using
std::vector,to make sure it was a win globally. Eliminating all copies here
may not be a win if iterating to find the element you want to
move to the front is ten time more expensive. (A lot of this
depends on how expensive
MyTypeis to copy, and how large itis. If
sizeof(MyType)is close to the size of a page, oraccessing
MyTypeends up accessing a lot of indirectlyallocated objects, the locality argument won’t hold.)
With an
std::vector, rather than the obviouserase/insertThis will result in less copies than the
erase(which copiesall of the following elements)
insert(which also copies allof the following elements—which means all of the elements,
because we are inserting at the beginning) pattern.