1 auto arr1 = [1,2,3,4,5,100]; 2 auto arr2 = [6,7,8,9,10]; 3 4 foreach (ref a, b; lockstep(arr1, arr2)) 5 { 6 a += b; 7 } 8 9 assert(arr1 == [7,9,11,13,15,100]); 10 11 /// Lockstep also supports iterating with an index variable: 12 foreach (index, a, b; lockstep(arr1, arr2)) 13 { 14 assert(arr1[index] == a); 15 assert(arr2[index] == b); 16 }
Lockstep also supports iterating with an index variable:
1 auto arr1 = [0, 1, 2, 3]; 2 auto arr2 = [4, 5, 6, 7]; 3 4 size_t n = arr1.length -1; 5 foreach_reverse (index, a, b; lockstep(arr1, arr2, StoppingPolicy.requireSameLength)) 6 { 7 assert(n == index); 8 assert(index == a); 9 assert(arr1[index] == a); 10 assert(arr2[index] == b); 11 n--; 12 } 13 14 auto arr3 = [4, 5]; 15 n = 1; 16 foreach_reverse (a, b; lockstep(arr1, arr3)) 17 { 18 assert(a == arr1[$-n] && b == arr3[$-n]); 19 n++; 20 }
Iterate multiple ranges in lockstep using a foreach loop. In contrast to zip it allows reference access to its elements. If only a single range is passed in, the Lockstep aliases itself away. If the ranges are of different lengths and s == StoppingPolicy.shortest stop after the shortest range is empty. If the ranges are of different lengths and s == StoppingPolicy.requireSameLength, throw an exception. s may not be StoppingPolicy.longest, and passing this will throw an exception.
Iterating over Lockstep in reverse and with an index is only possible when s == StoppingPolicy.requireSameLength, in order to preserve indexes. If an attempt is made at iterating in reverse when s == StoppingPolicy.shortest, an exception will be thrown.
By default StoppingPolicy is set to StoppingPolicy.shortest.
Limitations: The pure, @safe, @nogc, or nothrow attributes cannot be inferred for lockstep iteration. zip can infer the first two due to a different implementation.