std.algorithm for changing array values

Meta jared771 at gmail.com
Wed Jan 15 13:21:49 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);
> 	}
> }

Ranges in general don't work very well for modifying values in 
place. The Data structs are passed by value between functions, so 
any modifications made won't be reflected in the original array. 
Using ranges to modify values usually entails making a copy. You 
can still use std.algorithm to simplify the above code a bit, 
however:

void main()
{
     auto entries = [Data(1, 1), Data(2, 2)];
     auto pos = entries.countUntil!(d => d.key == 3);
     if (pos >= 0)
     {
         entries[pos].value = 42;
     }
     else
     {
	entries ~= Data(3, 42);
     }
     writeln(entries);
}

Basically, just to abstract away the loop.



More information about the Digitalmars-d-learn mailing list