digitalmars.D.learn - How to store unique values of array in another array
- Samir (17/17) Oct 18 2018 What is the proper way to find the unique values of an array and
- Adam D. Ruppe (8/10) Oct 18 2018 Right, it is actually a "range" - an object that generates the
- Samir (7/9) Oct 18 2018 Thanks. That did the trick. But if I may, what is the
- Adam D. Ruppe (5/6) Oct 18 2018 No difference. The compile will just transform o.f into f(o) if
- Samir (2/3) Oct 18 2018 Thanks again, Adam.
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
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
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
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
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