3

So my basic idea for doing that was this kind of loop :

std::array<int,10> t{};
for (int k = t.size()-1; k >= 0; k--)
    cout << t[k] << " ";

The problem is that the .size() method returns an std::array::size_type, which, from what i've read, could be larger than an int.

The problem is that size_type is unsigned, so when i do this :

for (auto k = t.size()-1; k >= 0; k--)
    cout << t[k] << " ";

It just loops infinitely because k can't be negative. So how would you iterate an std::array or std::vector backwars using a size_type variable ?

lairv
  • 109
  • 5
  • 5
    Using iterators is a "correct" way: https://stackoverflow.com/questions/3610933/iterating-c-vector-from-the-end-to-the-begin – sshashank124 Dec 28 '19 at 14:31
  • 1
    Precisely, [this](https://stackoverflow.com/a/24851790/6205379) answer. – Timo Dec 28 '19 at 14:32
  • I like the idea of a reverse range based for loop: [https://stackoverflow.com/a/54401349/487892](https://stackoverflow.com/a/54401349/487892) – drescherjm Dec 28 '19 at 14:37

2 Answers2

7

If for some reason iterators don't work, and you must use indexes for some reason:

for (auto k = t.size(); k > 0; )
{
    --k;

    // The rest of your loop
}
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
7

If you can use C++11 or higher, you could / should use iterators. Soething like this:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {1,2,3,4,5};
    for(auto it = v.rbegin(); it != v.rend(); ++it) {
        std::cout << *it << '\n';
    }

    return 0;
}

Live example here.

florestan
  • 4,405
  • 2
  • 14
  • 28