2

What is the best way to remove an element from std::list in c++ and place it at the end given an iterator to the current element and the list of course.

This is what I have written now and I am not sure is the best/ correct way of doing it:

void MyClass::update(std::list<T> * memSegs, std::list<T>::iterator it){

    memSegs -> splice(
        memSegs -> end(),
        *memSegs,
        it
    );
}
Saher Ahwal
  • 9,015
  • 32
  • 84
  • 152

2 Answers2

1

From what the cppreference tells me, This indeed seems optimal. Constant time, element is moved.

Xarn
  • 3,460
  • 1
  • 21
  • 43
1

If you do not care about the order of the other elements then the simplest solution is just to swap the element pointed to by it with the last element in the container.

std::swap(*it, memSegs->back());

Otherwise std::list::splice indeed seems to be the best choice.

For other containers as e.g. std::vector, and if you want to maintain order (swap if you don't care), then you can use std::rotate which has linear complexity.

std::rotate(it, std::next(it), std::end(*memSegs));
Felix Glas
  • 15,065
  • 7
  • 53
  • 82
  • nice idea +1. unfortunately, I care about the order. This is for an eviction policy I am implementing where the last element in the least recently used. – Saher Ahwal Feb 07 '14 at 16:45