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

2019-01-21 22:40发布

问题:

This question already has an answer here:

  • How do I erase an element from std::vector<> by index? 10 answers

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);

回答1:

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

To remove element with index i.



回答2:

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();


回答3:

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!



回答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 );


回答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.



标签: c++ vector