Note that std::map in C ++ is a sorted data structure, and the associative array in D is unordered. std.algorithm.setIntersection accepts a sorted range, so you cannot use this function until you convert an associative array to a sorted range, for example. ( result )
import std.typecons; import std.array; import std.algorithm; import std.stdio; auto byItemSorted(K,V)(V[K] dict) { auto app = appender!(Tuple!(K,V)[])(); foreach (k, v; dict) app.put(tuple(k, v)); auto res = app.data;
But this method is inefficient - O (N log N) is required to sort the range.
A more efficient method is to write your own intersection procedure, which only accepts O (N) ( result ):
import std.stdio; struct DictIntersection(K,V) { V[K] m1, m2; this(V[K] map1, V[K] map2) { m1 = map1; m2 = map2; } int opApply(int delegate(ref K, ref V) dg) { int res = 0; foreach (k, v; m1) { V* p = k in m2; if (p && v == *p) { res = dg(k, v); if (res) break; } } return res; } } DictIntersection!(K,V) dictIntersection(K,V)(V[K] map1, V[K] map2) { return typeof(return)(map1, map2); } void main () { auto map1 = ["red":4, "blue":6], map2 = ["blue":2, "green":1], map3 = ["blue":6, "purple":8]; write("map1 & map2 = "); foreach (k, v; dictIntersection(map1, map2)) write(k, "->", v, " "); write("\nmap1 & map3 = "); foreach (k, v; dictIntersection(map1, map3)) write(k, "->", v, " "); }
However, since opApply is not considered an input range, all range algorithms will not work with this. (I do not know how this can be done in the input range.)