views:

1413

answers:

2

If I have a std::vector and I want to delete the x'th element how to do it?

std::vector<int> vec;

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

vec.erase(???);

Please help!

+10  A: 

You could do

std::vector<int> vec;

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

vec.erase(vec.begin() + 1);

or

vec.erase(vec.begin() + 1, vec.begin() + 2);

to delete more then one element at once.

rstevens
+5  A: 

The erase method on std::vector is overloaded, so its probably clearer to call:

vec.erase(vec.begin() + index);

when you only want to erase a single element.

CodeBuddy