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
}
Megidd
  • 7,089
  • 6
  • 65
  • 142
  • 2
    This might help: https://stackoverflow.com/questions/8542591/c11-reverse-range-based-for-loop – vishal Jun 17 '19 at 06:13

1 Answers1

0

Use std::reverse.

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

This will add O(n) iterator swaps

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • Thanks. Is using `std::reverse` computationally more expensive than the traditional `for (int i = myContainer.size() - 1; i >= 0; --i)` method? – Megidd Jun 17 '19 at 06:30
  • 1
    Yes, O(n) iterator swaps are added – Thomas Sablik Jun 17 '19 at 06:34
  • 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`. – Megidd Jun 17 '19 at 06:38
  • Sorry but this is a bad solution. No one would modify the whole container just to iterate it backwards. – paceholder Jun 17 '19 at 10:11
  • @paceholder This is a correct answer to the question. You are free to provide a better answer. – Thomas Sablik Jun 17 '19 at 11:43
  • @ThomasSablik a better answer is provided [at the top-most link here](https://stackoverflow.com/questions/8542591/c11-reverse-range-based-for-loop). The question was how to perform a reversed iteration, not how to reverse the whole container and do a forward loop. I agree that your code could print-out elements in a desired order but it could be a performance kill. I had to warn anyone reading the answers that this solution is a bad one. Sorry, once again, nothing personal. – paceholder Jun 17 '19 at 12:51
  • @paceholder Adding boost to some projects can be an overkill. I'm currently working in a project where it's not possible to include boost. That's the reason why different solutions exist. In many cases where the loop has complexity O(n log n) or worse adding O(n) isn't that bad. – Thomas Sablik Jun 17 '19 at 12:54
  • @ThomasSablik O-notation is not the same as elapsed real time. Reversing a billion of "large" elements is very expensive. If boost is not allowed, one should stick to the classical reversed loop with indices or write a small wrapper-class implementing `begin()` as `rbegin()` and `end()` as `rend()`. – paceholder Jun 17 '19 at 13:13
  • @paceholder classical reversed loop was posted in the question. OP knows about that. The question is if there is a way to use a range based loop. My answer contains a solution and the extra costs. – Thomas Sablik Jun 17 '19 at 13:27
  • @ThomasSablik your solution does not work with a const container. – paceholder Jun 17 '19 at 13:46