9

How do I access the next element in range based for loop before the next loop?

I know with an iterative approach you do something like arr[++i], but how do I achieve the same result in a range-based for loop?

for (auto& cmd : arr) {
   steps = nextElement; //How do I get this nextElement before the next loop?
}

I understand I probably shouldn't be using a range-based for loop, but that's the requirement provided for this project.

theintellects
  • 1,320
  • 2
  • 16
  • 28

1 Answers1

9

If the range has contiguous storage (e.g. std::vector, std::array, std::basic_string or a native array), then you can do this:

for (auto& cmd : arr) {
    steps = *(&cmd + 1);
}

Otherwise, you can't, without an external variable.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • I suppose it's possible to use `std::find` without an external variable to track it down. It might take a bit of fiddling if you have more than one in the container, though. – chris Nov 14 '13 at 00:50
  • 3
    Note that you'll have to handle the case that `steps` is empty (i.e., if `cmd` is the last element) separately. – Patrick Jan 24 '20 at 12:24
  • This defeats every possible purpose, depends on storage type and has corner cases. Let's not do that. – rahman Sep 29 '20 at 10:07
  • This is obscure and elegantly allows to handle corner cases in loops which otherwise would suffer in readability from an external variable and it works for the listed types. Let do this! :-) – Johannes Overmann Nov 04 '21 at 21:35
  • 1
    This solution is broken. It has undefined behavior. You're reading past the last element of an array. – Guillaume Racicot Aug 02 '22 at 03:56