为什么 std::unique 不调用 std::sort?

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

本文关键字:std sort 调用 unique 为什么      更新时间:2023-10-16

C++11中的库算法std::unique可用于重新排列容器的输入范围,以消除相邻的重复条目,并返回一个迭代器,表示唯一值范围的结束。这意味着,如果我们想将其应用于容器,我们首先必须调用std::sort,然后调用std::unique,并以std::erase结束,如下例所示:

// 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());

我的问题是:std::unique不调用std::sort的原因是什么?谢谢

std::unique不调用std::sort的原因是什么?

因为如果输入容器已经排序,那么它是多余的并且效率低下。

std::unique的用例是这样的,它经常(至少偶尔(调用一个已经按排序顺序的序列。

相反,如果序列未排序,也没有问题:只需自己排序即可。换句话说,std::unique保持可组合。您建议的std::unique不太可组合。在某些情况下,它会执行不必要的工作,用户无法避免这种情况。