Print int[string] sorted by Value

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Oct 28 15:27:04 UTC 2020


On Wed, Oct 28, 2020 at 03:15:40PM +0000, Paul via Digitalmars-d-learn wrote:
> per the D sample wc2.d....
> size_t[string] dictionary;  <-is printed by...
> .....
> foreach (word1; dictionary.keys.sort) writef ....etc
> 
> I want to print the dictionary sorted by value not key.  I can write
> an algorithm but is there a library method(s) I can use to iterate
> through the array sorted by decreasing values?
[...]

Just use a different sorting predicate:

	import std;
	void main() {
		int[string] aa = [
			"abc": 321,
			"def": 234,
			"ghi": 524,
			"jkl": 310,
			"mno": 110,
			"pqr": 910,
		];

		foreach (key; aa.keys.sort!((a,b) => aa[a] < aa[b])) {
			writeln(key);
		}
	}


T

-- 
Curiosity kills the cat. Moral: don't be the cat.


More information about the Digitalmars-d-learn mailing list