so i have std::vector<> list;
now int i;
list.erase(i); doesn't work
so i have std::vector<> list;
now int i;
list.erase(i); doesn't work
list.erase(list.begin() + i);
list.erase() takes an iterator rather than an int index. But since vector iterators implement the random access concept, they're quite flexible. You can add an integer to any random access iterator, for example, and get a new iterator that is offset the appropriate number of indices from the original.
Note that if you haven't worked with iterators much, there are a variety of rules, different for each container, regarding when they become invalidated. With the above code, all iterators that you have saved off in variables elsewhere which point to any position in the vector at or after the erasure point become invalidated; you should not use them, or you'll experience the dreaded undefined behavior.
If only there were a website built entirely around answering simple programming questions and only if there were a place you could go to ask questions and have the entire Internet scoured for answers in a matter of milliseconds.
so i dont get it, does it mean i can erase something that is 1.5 from begin() then?
Do you mean deleting by value instead of index? So, something like
std::vector<float> values = {1.41f, 3.14f, 42.0f}; //Initialize vector with some values
values.erase(1.41f);
for(float v : values)
std::cout << v << std::endl;
And it would say 3.14f and 42.0f?
For that, you could just run through the vector and delete the value:
for(auto it = values.begin(); it != values.end(); it++)
if(*it == 1.41f) {
values.erase(it);
break;
}
Or, include <algorithm> and do this:
values.erase(std::find(values.begin(), values.end(), 1.41f);
std::find returns the iterator to the first item in the range ( values.begin(), values.end() ) that compares equal to the value (1.41f) that you provide.
Please note that in the example, I use floats, so it is hard to confuse the value with an index. However, comparing floats simply with the == operator is usually not optimal. That is an entirely different topic, I advise you to look it up.