Reputation: 1370
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.
Upvotes: 11
Views: 10380
Reputation: 103693
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.
Upvotes: 10