For my task, I'm using std::list<Key>
to maintain the order of elements in a makeshift LRU cache. So, one of the frequent operations is taking a list element out and putting it back on the list's front.
Obviously, it can be implemented by first using std::list::erase
and then std::list::push_front
. However, I don't like the idea of dealing with memory reallocation when all I wanna do is move a list node to a different position.
This is exactly what the extract
method allows us to do for std::map
, std::set
etc: taking a node out, modifying it and putting it back with no reallocation at all.
Is there a reasonable explanation why std::list
lacks the same functionality, and is there a workaround to mimic it with existing class API?
There is a std::list::splice
member function that might be what you want. It operates on the internal pointers of the list nodes. I don't see a way to splice from/to the same list but you could splice to a temporary (empty) std::list
and then splice back to the front of the original list.
On review, splicing is allowed within the same list. It is undefined to splice an entire list to itself. Splicing a single element into the same list is okay and splicing a range of elements is okay as long as the destination position isn't included in the spliced-from range. (Thank you, Daniel Langr)