Hi, I have the problem that I have an array which is changing during a loop and I have to skip certain elements.
What is the best way to do this?
a = [1,2,3]
itr = Iterators.Stateful(a)
for (i,el) in enumerate(itr)
@show el
if el == 2
deleteat!(a,i)
insert!(a,i,9)
insert!(a,i,8)
# remove extra iteration
popfirst!(itr)
end
end
a
# Output
el = 1
el = 2
el = 3
4-element Array{Int64,1}:
1
8
9
3
Generally Iterators.filter
is useful for that, but in this particular case: I don’t think that modifying the underlying vector is allowed (“undefined consequences”).
Make a copy of the array to iterate over while you modify the other one? And/or just use a while loop if there’s a clear termination condition.
1 Like
I’ll try to use a while loop. If length is calculated every iteration I think it should work.
i = 1
a=[1,2,3]
while i < length(a)
# change length and incr i
i += 1
end
Setting a flag to skip the next iteration combined with a continue
could also work, I think.
1 Like