Remove ith item from a C++ std::vector [duplicate]

Here is an O(1) solution, assuming you don’t care about the order of elements:

#include <algorithm>

// ...

{
    using std::swap;
    swap(pList[i], pList.back());
    pList.pop_back();
}

For PODs, assignment is faster than swapping, so you should simply write:

pList[i] = pList.back();
pList.pop_back();

In C++11, you can forget the above distinction and always use move semantics for maximum efficiency:

if (i != pList.size() - 1)
{
    // Beware of move assignment to self
    // see http://stackoverflow.com/questions/13127455/
    pList[i] = std::move(pList.back());
}
pList.pop_back();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)