How to traverse vector from end to start? [duplica

2019-07-28 10:19发布

问题:

Possible Duplicate:
Erasing elements from a vector

I want to delete some elements as I go and so dont want miss the iteration

I travers right now as follows

vector<double> distances;
for(size_t i=0; i<distances.size();i++)
{

}

How do I traverse from end to beginning so I can safely delete elements and yet access the element I want?

回答1:

for (size_t i = distances.size() - 1; i >=0; --i)

However, you should use an std::remove_if instead



回答2:

The best way to handle this is to cheat, actually.

In C++, we have the erase/remove idiom to have the most efficiency. You create a predicate and then you're on, and it's gotten quite simple with lambdas now.

// This removes all odd elements in vec
vec.erase(vec.remove_if([](int i) { return i % 2 == 1 }), vec.end();

The way remove_if works is that it shuffles elements around (either copying or moving) so as to gather all the elements you wished to keep at the head of the container, the tail being left in an unspecified (but valid) state, and then returns to you an iterator to the first element of the tail.

By then using the range-erase method of the container, you ask the container to remove all those elements in one go.



回答3:

use the reverse_iterator :

vector<something>::reverse_iterator iter = v.rbegin();
iter++; //Iterates backwards


标签: c++ vector