Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing next element in range based for loop before the next loop

Tags:

c++

loops

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.

like image 826
theintellects Avatar asked Nov 14 '13 00:11

theintellects


People also ask

What is a ranged based for loop?

Range-based for loop in C++It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

Are range-based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once.

How do I get the previous number in Python?

Use enumerate() to access previous and next values in a list. Loop over enumerate(list) in a for loop with the syntax for index, elem in enumerate(list) . To access the next element in list , use list[index+1] and to access the previous element use list[index-1] .

What does auto do in a for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression.


1 Answers

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.

like image 185
Benjamin Lindley Avatar answered Oct 31 '22 19:10

Benjamin Lindley