On Thu, 20 Oct 2011 21:49:27 -0400, bearophile <bearophileh...@lycos.com>
wrote:
I have many strings and I want to use as associative array kay a sorted
concat of two strings (it's a signature of the two strings):
import std.algorithm;
void main() {
string a = "red";
string b = "green";
int[string] aa;
//aa[(a ~ b).sort] = 1;
//aa[(a ~ b).sort.idup] = 1;
aa[(a.dup ~ b.dup).sort.idup] = 1;
}
I think the first way used to work, the second way was recently
forbidden (and you can't use char[] as associative array key). The third
way now works, but array.sort will go away.
So do you know what's a copy-minimizing (and possibly short) way to
perform this, in future?
a ~ b should technically be assignable to char[], since it's alread new
memory. We may yet get there with pure functions being able to implicit
cast to immutable.
You could do this for now, but it's ugly:
char[] concatStr(string[] s...) pure
{
auto len = 0;
foreach(str; s) len += str.length;
auto result = new char[len];
auto slice = result;
foreach(str; s)
{
slice[0..str.length] = str;
slice = slice[str.length..$];
}
return result;
}
...
auto str = concatStr(a, b);
str.sort; // this is going to stop working, you'll have to cast to byte[]
aa[assumeUnique(str)] = 1;
There are also alternatives to AA (such as dcollections' HashMap) which
are willing to take non-immutable keys.
-Steve