Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding maximum valued element in a Associative Arrays in D

Tags:

d

After reading docs about ranges , I believe any std.algorithm function should work with any container include associative arrays ,

But the code below fails :

double[double] freqIntensity;
foreach (complexval; resultfft)
{
    freqIntensity[arg(complexval)]++;
}
minPos!("a > b")(freqIntensity);

with error :

src\main.d(56): Error: template std.algorithm.minPos does not match any function template declaration. Candidates are:
C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(6321):        std.algorithm.minPos(alias pred = "a < b", Range)(Range range) if (isForwardRange!(Range) && !isInfinite!(Range) && is(typeof(binaryFun!(pred)(range.front, range.front))))
src\main.d(56): Error: template std.algorithm.minPos(alias pred = "a < b", Range)(Range range) if (isForwardRange!(Range) && !isInfinite!(Range) && is(typeof(binaryFun!(pred)(range.front, range.front)))) cannot deduce template function from argument types !("a > b")(double[double])
src\main.d(56): Error: template instance minPos!("a > b") errors instantiating template

Ofcourse I can iterate or do other tricks , but I don't want to do the same mistakes as I did in C++(like writing C code in C++), I want , features of language to work for me. What is the best way to find the maximum valued element of associative array.

like image 310
Kadir Erdem Demir Avatar asked Sep 15 '13 13:09

Kadir Erdem Demir


1 Answers

Use byValue to avoid a copy. Note this works in HEAD and will be deployed with the next release.

import std.stdio, std.algorithm;

void main() {
    double[double] freqIntensity = [1.0 : 2.0, 2.3 : 8.9];
    writeln(minPos!("a > b")(freqIntensity.byValue));   
}
like image 81
Andrei Alexandrescu Avatar answered Sep 20 '22 01:09

Andrei Alexandrescu