Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

I have a std::vector<int>, and I need to erase the n'th element. How would I do that?

std::vector<int> vec;

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

vec.erase(???);
by

2 Answers

akshay1995
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(std::next(vec.begin()));

Or, to delete more than one element at once:

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3));
RoliMishra
The erase method will be used in two ways:

Erasing single element:

vector.erase( vector.begin() + 3 ); // Deleting the fourth element


Erasing range of elements:

vector.erase( vector.begin() + 3, vector.begin() + 5 ); // Deleting from fourth element to sixth element

Login / Signup to Answer the Question.