Search code examples
c++algorithmsortingc++11unique

Why doesn't std::unique call std::sort?


The library algorithm std::unique in C++11 can be used to rearrange an input range of a container to eliminate adjacent duplicated entries, and returns an iterator that denotes the end of the range of the unique values. This implies that if we would like to apply this to a container, we would first have to call std::sort, then std::unique and finish with std::erase as in the following example:

// sort words (vector<string>) alphabetically so we can find the duplicates 
sort(words.begin(), words.end());

// unique reorders the input range so that each word appears once in the
// front portion of the range and returns ab iterator one past the unique range
auto end_unique = unique(words.begin(), words.end());

// erase uses a vector operation to remove the non-unique elements
words.erase(end_unique, words.end());

My question is: what's the reason for std::unique not calling std::sort? Thanks!


Solution

  • what's the reason for std::unique not to call std::sort?

    Because it’s redundant and inefficient if the input container was already sorted.

    The use-case of std::unique is such that it’s often (more than occasionally, at any rate) called on a sequence which is already in sorted order.

    Conversely, if the sequence is unsorted, that’s no problem either: just sort it yourself. In other words, std::unique is kept composable. Your suggested std::unique is less composable. It performs unnecessary work in some situations, and there’s nothing the user could do to avoid this.