Search code examples
c++arrayssortingunique

How unique() function for array works


int a[4] = {3,1,2,3};
sort(a,a+n);
int j = unique(a,a+n) - a; // j=3

In this code variable j returns total numbers of unique element in the array a. But I couldn't understand how this code is working.

I know that in lists,
list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive elements from the list.


Solution

  • std::unique() is going to move the duplicates in the range [a+0, a+n), and it returns a new iterator in that range that will mark the new "end" of the array, i.e, where the first non-unique item is now moved to in the array.

    If you then subtract from that iterator the beginning iterator, which you do with unique(a,a+n) - a;, you get the number of elements that are between the start of the array and the new "end". This is how you are able to get the count of the unique elements.

    It should be noted that I use "end" here because arrays have a fixed size. You aren't actually changing the size of the array at all, you are just moving the duplicate elements to the back of the array, and keeping the unique elements at the front.

    It should also be noted that after this happens, everything at and after the iterator returned by unique() will have an unspecified value. It is legal to set new values to them, but using an unspecified value leads to undefined behavior.