dau_man dau_man - 2 months ago 11
C++ Question

How to erase element from std::vector<> by index?

I have a std::vector, and I want to delete the n'th element. How do I do that?

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

vec.erase(???);


Please help!

Answer

To delete a single element, you could do:

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);

Or, to delete more then one element at once:

// Deletes the 2nd through 3rd elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);