std.algorithm for changing array values

TheFlyingFiddle kurtyan at student.chalmers.se
Wed Jan 15 12:50:16 PST 2014


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)];
> 	bool found;
>
> 	foreach(entry;entries){
> 		if (entry.key == 3){
> 			entry.value = 42;
> 			found = true;
> 		}
> 	}
>
> 	if (found == false){
> 		entries ~= Data(3,42);
> 	}
> }


You can use canFind.

import std.algorithm;

struct Data{
    int key;
    int value;
}

void main()
{
    auto entries = [Data(1,1),Data(2,2)];

    if(!entries.canFind!(x => x.key == 3))
       entries ~= Data(3, 42);
}



More information about the Digitalmars-d-learn mailing list