by thewebcount · 6y ago · 0 comments
for (auto x : someContainer) { //do something with x }
But inevitably, I end up needing either an iterator pointing to a particular item at the end, or I need an index to pass to some other function, and this style makes that impossible. Perhaps it's just the domain I work in, but even after years of trying to make this work, it still only works about half the time for what I'm doing.while (my ($index, $value) = each @list) { ... }
https://docs.raku.org/routine/kv#class_List
for @list.kv -> $index, $value { ... }
map someFunction listOfValue
if you need an index: map someOtherFunction (zip [0..] listOfValues)
Python uses 'enumerate' to similar effect. Not sure if C++ has an equivalent? zipWith someOtherFunction [0..] listOfValues
# , since someOtherFunction is likely to be
# :: (Int -> Value -> Stuff) rather than
# :: ((Int,Value) -> Stuff) .
zipIndex f = zipWith f [0..]
# is also often useful.In eg OCaml you have to use something like zipIndex (but implemented differently) or mapWithIndex, because they don't do lazy data structures by default. (And in eg Python their lazy sequences come with lots of caveats because they are not referentially transparent.)
Just change your loop to auto& x.