【问题标题】:Do I have the guarantee that std::unique will keep the first element?我是否保证 std::unique 将保留第一个元素?
【发布时间】:2014-06-05 05:39:58
【问题描述】:

考虑基于pair 的第一个元素的比较排序的std::vector<std::pair<int, int>>

现在假设我申请:

std::unique(std::begin(v), 
            std::end(v), 
            [](const std::pair<int, int>& x, const std::pair<int, int>& y)
            {return x.first == y.first;});

我能保证std::unique 将保留每个相等范围的第一个元素吗?

【问题讨论】:

    标签: c++ c++11 unique standards stl-algorithm


    【解决方案1】:

    是的。

    从范围 [first, last) 中的每个连续等效元素组中删除除第一个元素之外的所有元素,并为范围的新逻辑结束返回一个结束迭代器。

    From here.

    您给出的BinaryPredicate 只是意味着任何y 等于前一个元素x 的元素都将被删除。

    【讨论】:

      【解决方案2】:

      是的。 The C++14 draft standard 在第 25.3.9 节 [alg.Unique] 中说(强调我的):

      效果:对于非空范围,从 [first + 1,last) 范围内的迭代器 i 引用的每个连续等效元素组中删除除第一个元素之外的所有元素,其中以下条件成立:*(i - 1) == i 或 pred((i - 1), *i) != false。

      标准的引用在这里很重要,因为通常的互联网资源在这一点上给出了两个不同的答案:en.cppreference.com 不提供保证,但 cplusplus.com(引用 Ben above 有保证。)

      【讨论】:

        猜你喜欢
        • 2010-10-25
        • 2013-10-22
        • 1970-01-01
        • 2020-05-26
        • 2018-01-02
        • 1970-01-01
        • 2021-05-13
        • 2020-05-27
        相关资源
        最近更新 更多