37

How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

pList.remove(i);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kralco626
  • 8,456
  • 38
  • 112
  • 169

5 Answers5

88

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();
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
63
pList.erase(pList.begin()+i);

To remove element with index i.

Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • Thanks! I didn't understand how to get an iterator to pass to the method... – kralco626 Dec 14 '10 at 18:09
  • 4
    one note, the behavior is undefined if the `vector` contains less than `i+1` elements. It's probably worth noting :) – Matthieu M. Dec 14 '10 at 18:49
  • Note that this will preserve the order of elements, and is O(n). If you don't need to preserve order, use the O(1) solution mentioned by others. – Joe May 24 '17 at 01:25
15

An approach to save yourself from linear complexity!

Since vector.erase() is linear complexity, I would suggest that just swap the ith element with the last element and then erase the element at the end (which is actually ith element); that way, you possibly can save yourself from linear complexity. That is just my thought!

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    "vector.erase() is linear complexity" Is there a book with a tabler for such things? I keep getting an impression that such estimates need a thorough knowledge of some algorithms (but I still hope there is a table with methods complexity for each data type somewhere). Thanks. –  Nov 17 '12 at 03:56
5
vector.erase(iterator)

Where iterator is the position. You can get the first element with vector.begin() and the last one with vector.end(). Just add to the iterator to get to the desired element. e.g.:

pList.erase(pList.begin()+6);

to erase the 6th item.

Tom Johnson
  • 497
  • 1
  • 7
  • 16
4

Use Vector.Erase. The complexity is linear on the number of elements erased (destructors) plus the number of elements after the last element deleted (moving).

iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );
Sonny Saluja
  • 7,193
  • 2
  • 25
  • 39