How to Peek At the Next Element in a Range-For Loop

Is it possible to peek at the next element in a range-for loop?

Is it possible to peek at the next element

In general case - no.

Since objects in std::vector are stored contiguously, you could do *(&my_int + 1), but if you change the container later, the code might silently break. Don't do that!


And to check if the current element is the last one, you could use &my_int == &my_ints.back().

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

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.

checking next element in for loop

for i in range(len(arr)):
if arr[i] == "foo":
if arr[i+1] == 'bar':
print arr[i] + arr[i+1]
else:
print arr[i]

How to access next element in a list using a for loop [duplicate]

You can use enumerate:

for idx, i in enumerate(nums):
print(i) # print current item
if idx < len(nums) - 1: # check if index is out of bounds
print(nums[idx+1])

Concerning your follow up question on how to handle two elements per list iteration, without repeating any elements, you can use range with a step of 2, e.g.

for idx in range(0, len(nums), 2):
print(nums[idx])
if idx < len(nums) - 1:
print(nums[idx+1])

How to access the next element in for loop in current index/iteration?

You can access any member of the list if you iterate by index number of the array vice the actual element:

for i in range(len(vocab_list)-1):
for j in range(len(sentence)-1):
if(vocab_list[i]==sentence[j] and vocab_list[i+1]==sentence[j+1]):
print "match"

Get the previous or next item in a map from a for loop

No. key is not an iterator.

for (auto const& [key, val] : oper_map)

key is a const reference to the key in the map. If you want iterators, use iterators:

for (auto it = oper_map.begin(); it != oper_map.end(); ++it) {
auto next = std::next(it);
auto prev = std::prev(it);
}

However, consider that std::map is not a sequential container. If you are interested in the positions of elements in the container, maybe a std::vector< std::pair<Key,MappedValue>> is more handy (note that complexity of std::next is linear for bidirectional iterators (map) while it is constant for random access iterators (vector), same is true for std::prev).

Access next item of a range from within a for loop (Excel VBA)

Do it in two passes:

  1. get the information
  2. loop over the information

For example:

Sub dural()
Dim boo() As Boolean, Rng As Range, i As Long, iMax As Long
Set Rng = Range("A2:A105").SpecialCells(xlCellTypeVisible)
ReDim boo(1 To Rng.Count)

i = 1
For Each rowcheck In Rng
If Cells(rowcheck.Row, "C").Interior.Color = RGB(191, 191, 191) Then
boo(i) = True
Else
boo(i) = False
End If
i = i + 1
Next rowcheck
iMax = i - 2

For i = 1 To iMax
If boo(i) And boo(i + 1) Then
'whatever
End If
Next i

End Sub

Loop that also accesses previous and next values

This should do the trick.

foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
if obj == foo:
if index > 0:
previous = objects[index - 1]
if index < (l - 1):
next_ = objects[index + 1]

Here's the docs on the enumerate function.

Getting next element while cycling through a list

After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break, which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that li be a list or tuple. It could be any iterator.

from itertools import cycle

li = [0, 1, 2, 3]

running = True
licycle = cycle(li)
# Prime the pump
nextelem = next(licycle)
while running:
thiselem, nextelem = nextelem, next(licycle)

I'm leaving the other solutions here for posterity.

All of that fancy iterator stuff has its place, but not here. Use the % operator.

li = [0, 1, 2, 3]

running = True
while running:
for idx, elem in enumerate(li):
thiselem = elem
nextelem = li[(idx + 1) % len(li)]

Now, if you intend to infinitely cycle through a list, then just do this:

li = [0, 1, 2, 3]

running = True
idx = 0
while running:
thiselem = li[idx]
idx = (idx + 1) % len(li)
nextelem = li[idx]

I think that's easier to understand than the other solution involving tee, and probably faster too. If you're sure the list won't change size, you can squirrel away a copy of len(li) and use that.

This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running in the middle of the for loop and then break.



Related Topics



Leave a reply



Submit