Vector subscript out of range when looping backwards

Hello there! To be honest, I'm in a bit of a pickle. Have you ever looped through a vector, only to be struck by a vector subscript out of range? Well, if I'm not mistaken, they come from this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  std::vector<std::vector<int>> first;
  std::vector<std::string> second;

  // All vectors get properly initialized here
  // ...
  // And then we loop - or at least we try to:

  for (size_t i = (second.size() - 1); i >= 0; --i)
  {
    // Some code here...
  }

  for (size_t i = (first.size() - 1); i >= 0; --i)
  {
    for (size_t j = (first[i].size() - 1); j >= 0; --j)
    {
      // Some other code here...
    }
  }


Now, both of these for loops cause a "vector subscript out of range". If I rewrite them like this...

1
2
3
4
  for (size_t i = (second.size() - 1); i > 0; --i)
  {                  /* The only change ^^^ */
    // Same old code here...
  }


...they don't cause anything weird, but, as one might expect, second[0] gets skipped. I tried googling around, but the only thing I came across are people using these loops with no problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>

int main()
{
    const std::vector<int> vec { 11, 13, 16, 20, 25, 31, 38 } ;
    const auto sz = vec.size() ;
    
    for( std::size_t i = 0 ; i < sz ; ++i ) std::cout << vec[sz-i-1] << ' ' ;
    std::cout << '\n' ;

    for( std::size_t i = sz ; i > 0 ; --i ) std::cout << vec[i-1] << ' ' ;
    std::cout << '\n' ;

    for( auto iter = vec.rbegin() ; iter != vec.rend() ; ++iter ) std::cout << *iter << ' ' ;
    std::cout << '\n' ;
    
    // see link below for:
    // std::for_each ...
    // for( int v : in_reverse(vec) ) ...
}

http://coliru.stacked-crooked.com/a/79662d5c402a2d40
These do indeed work. Thank you.
Topic archived. No new replies allowed.