0

I was experimenting around with range-based for loop found that if you use range-based for loop to loop through a vector it runs into out of range error is there any way to avoid this error if you are using range-based for loop

int main()
{
    vector<int> num{ 1,2,3,4,5 };
    for (auto i : num)
    {
        cout << num[i] << endl;
    }
}

it shows this error

enter image description here

AUNG
  • 39
  • 7

2 Answers2

5

It's nothing to do with the type of loop. Your loop looks at all the values i inside the vector num, then it prints num[i]. One of them is 5, so it prints num[5]. But num has 5 elements so they only go up to num[4]. Out of range.

user253751
  • 57,427
  • 7
  • 48
  • 90
1
template<class It>
struct indexer {
  It it;
  It operator*()const{return it;}
  void operator++(){++it;}
  void operator++(int){++it;}
  bool operator==(indexer const& o)const{ return it == o.it; }
  bool operator!=(indexer const& o)const{ return it != o.it; }
};
template<class It>
struct range {
  It b,e;
  It begin()const{return b;}
  It end()const{return e;}
};
range<indexer<std::size_t>> counting( std::size_t begin, std::size_t end ) {
  std::cout << begin << "->" << end << "\n";
  return {{begin}, {end}};
}

template<class X>
auto indexes_of( X const& x ) {
  using std::size;
  return counting(0, size(x));
}

now I can make your code do what you thought it did:

vector<int> num{ 1,2,3,4,5 };
for (auto i : indexes_of(num))
{
    cout << num[i] << endl;
}

Live example.

Your problem was mistaking indexes into the vector for the elements. Range-for returns the elements. indexes_of makes it return the indexes for the container in question.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524