Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning unique() function in C++

I came across the following function, which sorts an array passed down by main(), removes duplicates, and returns the number of unique elements. It's the last bit I'm having a hard time wrapping my head around.

int reduce(long ar[], int n) {
  sort(ar, ar + n);
  return unique(ar, ar + n) - ar; // ??? 
}

To my understanding unique() returns a pointer to the end of the segment that stores the unique values in the array. But I don't see why subtracting the array name from the iterator results in an int that equals the number of unique elements, or why unique(ar, ar+n) can't be typecasted to int to achieve the same result.

like image 334
Leon Avatar asked Jun 27 '26 10:06

Leon


1 Answers

why unique(ar, ar+n) can't be typecasted to int to achieve the same result.

Because, as you said, unique returns a pointer. A pointer is a memory address, not an index. So casting a pointer to an int is meaningless.

why subtracting the array name from the iterator results in an int that equals the number of unique elements

Subtracting two pointers (into the same array) evaluates to the number of elements between them.*


* As pointed out by @Nawaz in comments below, this result is signed. So (p1 - p2) == -(p2 - p1).
like image 136
Oliver Charlesworth Avatar answered Jun 29 '26 22:06

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!