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);
The erase() function can remove an element from the beginning, within, or end of the vector. In order to remove all the elements from the vector, using erase(), the erase() function has to be repeated the number of times there are elements, beginning from the first element.
clear() function is used to remove all the elements of the vector container, thus making it size 0.
To delete single element from a vector using erase() function, pass the iterator of element to it like erase(it). It will delete the element pointed by the iterator the it variable. To delete multiple elements from a vector using erase() function, pass the iterator range to it like erase(start, end-1).
pList.erase(pList.begin()+i);
To remove element with index 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With