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.
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.*
(p1 - p2) == -(p2 - p1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With