Comment #0 by bearophile_hugs — 2011-10-20T18:32:34Z
"Given an unsorted array, remove the duplicate items" is a common need. In std.algorithm there are tools to perform this task with a very limited amount of code:
import std.algorithm;
void main() {
auto items = [3, 1, 5, 2, 3, 1];
items.length -= copy(uniq(items.sort()), items).length;
assert(items == [1, 2, 3, 5]);
}
(If you see better solutions feel free to add a comment.)
It's a single line of code, but in my opinion it's not obvious code, and it repeats the name "items" three times (this makes it a bit bug prone).
Removing the duplicated items from an unsorted array is a common operation, so maybe it's worth adding this pattern as a function, named like std.array.sortedUnique or something similar.
(Other ways to create an array of unique items is to use hashing, but this is better left to other functions.)
Comment #1 by bearophile_hugs — 2012-11-28T17:33:25Z
I meant something like this:
T[] unique(T)(T[] items) /*pure nothrow*/ {
items.length -= items.sort().uniq().copy(items).length;
return items;
}