0

Reverse iteration from last item to first item can be done like this:

for (int i = myContainer.size() - 1; i >= 0; --i) {
    // Do
}

How can I reverse a ranged-based for loop:

for (auto i : myContainer) {
    // Do
}
1

1 Answer 1

0

Use std::reverse.

std::reverse(std::begin(myContainer), std::end(myContainer));
for (auto i : myContainer) {
    // Do
}

This will add O(n) iterator swaps

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks. Is using std::reverse computationally more expensive than the traditional for (int i = myContainer.size() - 1; i >= 0; --i) method?
Yes, O(n) iterator swaps are added
Right. I think I might stick to the traditional for (int i = myContainer.size() - 1; i >= 0; --i) to avoid the added expense of std::reverse.
Sorry but this is a bad solution. No one would modify the whole container just to iterate it backwards.
@paceholder This is a correct answer to the question. You are free to provide a better answer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.