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 开发者_如何学Pythonthe following:
pList.remove(i);
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();
pList.erase(pList.begin()+i);
To remove element with index i.
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!
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.
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 );
精彩评论