Use the vector::erase
function to erase an element, or range of elements from a vector. It returns an iterator pointing to the element after the last one erased:
v.erase(v.begin() + pos); v.erase(v.begin() + start, v.begin() + end);
For example, this program populates a vector with the numbers 0 to 9 and then erases 8, before erasing 3 to 5:
#include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { typedef std::vector<int> intvec; intvec v(10); std::iota(v.begin(), v.end(), 0); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; std::cout << "erase 8:\n"; intvec::const_iterator it = v.erase(v.begin() + 8); std::cout << "next element is " << *it << "\n"; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; std::cout << "erase 3 to 5:\n"; it = v.erase(v.begin() + 3, v.begin() + 6); std::cout << "next element is " << *it << "\n"; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
You can make a generic function to erase from a container by index by using std::advance
to move to the first (and optionally last) element to remove and then calling the container’s own erase
method:
template <class Container> typename Container::iterator erase(Container& cont, size_t pos, size_t len = 1) { typename Container::iterator it1 = cont.begin(); std::advance(it1, pos); typename Container::iterator it2 = it1; std::advance(it2, len); return cont.erase(it1, it2); }
Use it like this:
erase(vec, 8); // erase 8 erase(vec, 3, 3); // erase 3 to 5
Note that this will be O(n) for list
s because their iterators are not RandomAccessIterator
s.