How would I sort an associative array by value?

Ludovit Lucenic llucenic at gmail.com
Sat Sep 7 00:25:29 PDT 2013


On Friday, 6 September 2013 at 16:57:09 UTC, H. S. Teoh wrote:
> You mean you want to sort the stats.keys by the values they are 
> mapped
> to?
>
Yes, this exactly I wanted to do.
> What about:
>
> 	import std.array, std.algorithm, std.stdio, std.typecons;
> 	
> 	// I don't know what your original struct was, this one is just
> 	// for example.
> 	struct TestTuple {
> 		string name;
> 	}
> 	
> 	void main() {
> 		int[TestTuple] stats;
> 	
> 		// Make some sample data for testing
> 		stats[TestTuple("test1")] = 10;
> 		stats[TestTuple("test2")] = 4;
> 		stats[TestTuple("test3")] = 8;
> 		stats[TestTuple("test4")] = 11;
> 	
> 		// Sort by stats. If you want to sort by name instead,
> 		// change "a[0] < b[0]" to "a[1] < b[1]".
> 		foreach (t; stats.keys
> 				.map!((a) => tuple(stats[a], a))
> 				.array
> 				.sort!((a,b) => a[0] < b[0]))
> 		{
> 			auto stat = t[0];
> 			auto test = t[1];
> 			writeln(test, " = ", stat);
> 		}
> 	}
>
> The built-in AA's are inherently unordered, so they cannot be 
> sorted
> directly. You have to explicitly put the keys / values into an 
> array and
> sort that.
>
>
> T

Thank you, your code makes perfect sense. I'm still kinda 
discovering beauty of D.

Ludovit


More information about the Digitalmars-d-learn mailing list