【问题标题】:Why doesn't std::unique call std::sort?为什么 std::unique 不调用 std::sort?
【发布时间】:2020-11-03 13:16:10
【问题描述】:

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 的原因是什么? 谢谢!

【问题讨论】:

    标签: c++ algorithm sorting c++11 unique


    【解决方案1】:

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

    因为如果输入容器已经排序,那就是多余且低效的。

    std::unique 的用例是这样的,它经常(至少偶尔,无论如何)在一个已经排序的序列上调用。

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

    【讨论】:

    • 另外不要忘记每个任务都需要有一个单独的模块。所以,排序不是(也不应该是)std::unique 的任务 :)
    • 如果std::unique 被定义为不保留订单,那么您需要另一个保留订单的函数(或作为参数的标志)。class="comcopy">跨度>
    • 另外,std::unique 采用一对前向迭代器。 std::sort 需要随机访问,因此受到更多限制。你可以在链表上使用std::unique;你不能在链表上使用`std::sort。
    猜你喜欢
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    相关资源
    最近更新 更多