std.algorithm for changing array values

anonymous anonymous at example.com
Wed Jan 15 12:59:55 PST 2014


On Wednesday, 15 January 2014 at 20:54:06 UTC, anonymous wrote:
> On Wednesday, 15 January 2014 at 20:34:32 UTC, Andre wrote:
>> Hi,
>>
>> I checked std.algorithm but have no glue which
>> functions I can use to rewrite following code
>> with some nice algorithm functions.
>>
>> I have an array of structs. I want to check for
>> a specific key and if found I change the value.
>> If it is not found I add the entry.
>>
>> Kind regards
>> André
>>
>>
>> struct Data{
>> 	int key;
>> 	int value;
>> }
>>
>> void main(){
>> 	Data[] entries = [Data(1,1),Data(2,2)];
[...]
>
> If you want to stop after the first match:
>
> auto f = entries.find!(d => d.key == 3);
> if(f.empty) entries ~= Data(3,42);
> else f.front.value = 42;
>
> If there can be duplicates and you want to change them all:
>
> auto f = entries.filter!(d => d.key == 3);
> if(f.empty) entries ~= Data(3,42);
> else foreach(ref e; f) e.value = 42;

PS: You might want to consider using a different data structure
with better performance. An associative array for example:

int[int] entries = [1: 1, 2: 2];
entries[3] = 42;


More information about the Digitalmars-d-learn mailing list