How to return a reference to structs?
Ali Çehreli
acehreli at yahoo.com
Sun Nov 7 03:30:13 UTC 2021
On 11/6/21 8:57 AM, Andrey Zherikov wrote:
> On Saturday, 6 November 2021 at 13:57:47 UTC, Ali Çehreli wrote:
>> Have you considered std.range.indexed, which should at least cover the
>> case of accessing:
>>
>> https://dlang.org/phobos/std_range.html#indexed
>
> I don't need to iterate over whole collection, but subset of it.
'indexed' does not iterate the collection; just the ones that are in the
index array. For example, if you have 2 size_t elements in the index
array, 'indexed' will touch just two elements.
> As of now I need to be able to iterate over the arguments
> within a group as well as those that satisfy some condition.
It turns out 'indexed' provides access by reference; so you can even
mutate the elements:
import std.algorithm;
import std.range;
import std.stdio;
void main() {
int[] numbers = [ 0, 1, 2, 3, 4, 5 ];
size_t[] specials = [ 1, 5 ];
size_t[] moreSpecials = [ 2, 3, 4 ];
numbers.indexed(specials).each!((ref n) => n *= 10);
writeln(numbers);
}
The output shows elements 1 and 5 are multiplied by 10:
[0, 10, 2, 3, 4, 50]
I am happy with that solution. ;)
Of course you can use foreach instead of 'each' and apply some filtering
condition, etc.
Ali
More information about the Digitalmars-d-learn
mailing list