www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to store unique values of array in another array

reply Samir <samir aol.com> writes:
What is the proper way to find the unique values of an array and 
store them in another array?  When I try:

import std.stdio: writeln;
import std.conv;
import std.algorithm;

void main() {
     int[] unsortedArray = [5, 3, 8, 5, 2, 3, 0, 8];
     int[] uniqueArray;

     uniqueArray = uniq(sort(unsortedArray));
}

I get the compilation error:
sortSetUnique2.d(9): Error: cannot implicitly convert expression 
uniq(sort(unsortedArray)) of type UniqResult!(binaryFun, 
SortedRange!(int[], "a < b")) to int[]

which leads me to believe that the output of `uniq` is not 
necessarily another integer array.

Thanks
Oct 18 2018
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 18 October 2018 at 18:39:18 UTC, Samir wrote:
 which leads me to believe that the output of `uniq` is not 
 necessarily another integer array.
Right, it is actually a "range" - an object that generates the result on-demand, so it doesn't do work you don't actually need. If you don't need an array per se, you can just foreach over it and print them or further work on it without the cost of creating a new array. But, if you need to copy it into a new array, use `.array` at the end.
Oct 18 2018
parent reply Samir <samir aol.com> writes:
On Thursday, 18 October 2018 at 18:53:06 UTC, Adam D. Ruppe wrote:
 But, if you need to copy it into a new array, use `.array` at 
 the end.
Thanks. That did the trick. But if I may, what is the difference between uniqueArray = uniq(sort(unsortedArray)).array; and uniqueArray = unsortedArray.sort().uniq.array; They both seem to work. Is one preferred over the other?
Oct 18 2018
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 18 October 2018 at 19:19:53 UTC, Samir wrote:
 They both seem to work.  Is one preferred over the other?
No difference. The compile will just transform o.f into f(o) if it can. They both do the same thing and it is just a different way of writing it. Which is better simply depends on which one reads better to you.
Oct 18 2018
parent Samir <samir aol.com> writes:
On Thursday, 18 October 2018 at 19:25:26 UTC, Adam D. Ruppe wrote:
 Which is better simply depends on which one reads better to you.
Thanks again, Adam.
Oct 18 2018