Kadir Erdem Demir
Kadir Erdem Demir

Reputation: 3595

Finding maximum valued element in a Associative Arrays in 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.

Upvotes: 5

Views: 153

Answers (2)

Andrei Alexandrescu
Andrei Alexandrescu

Reputation: 3216

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));   
}

Upvotes: 4

fwend
fwend

Reputation: 1853

An associative array is not a range, you have to pass in the values

import std.stdio, std.algorithm;

void main() {
    double[double] freqIntensity = [1.0 : 2.0, 2.3 : 8.9];
    writeln(minPos!("a > b")(freqIntensity.values));   
}

Upvotes: 3

Related Questions