为什么 std::unique 不调用 std::sort?
Why doesn't std::unique call std::sort?
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
不太可组合。在某些情况下,它会执行不必要的工作,用户无法避免这种情况。
相关文章:
- std::sort()函数无法对向量的一部分进行排序
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- C++中"std::sort"比较器的不同类型
- 将用户定义的类型与 std::vector 和 std::sort 一起使用
- 使用 std::sort 对向量进行稳定排序
- std::sort 如何处理重复的数字?
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- 使用 std::sort 对二维 c 数组进行排序
- std::stable_sort vs std::sort
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- std::vector 未按 std::sort 的预期排序
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 为什么只有当我的容器有超过 32 个元素时才由 std::sort 调用交换?
- 在 c++ 中使用 std::sort 与迭代器和模板
- 使用类似的比较函数时,在 c++ 中为 std:sort 获得不同的结果
- 相同的结果 qsort vs std::sort
- 通过 std::sort 对 C 2D 数组进行排序
- 对整个范围进行排序时,std::p artial_sort() 与 std::sort() 的性能?
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 使用 std::sort 对矩阵进行排序