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 to call std::sort? Thanks!
Aucun commentaire:
Enregistrer un commentaire