首页 > 解决方案 > 为什么 std::inlcudes 在条件中使用小于运算符而不是相等运算符?

问题描述

std::includes我有来自https://en.cppreference.com/w/cpp/algorithm/includes的算法实现

template<class InputIt1, class InputIt2>
bool includes(InputIt1 first1, InputIt1 last1,
              InputIt2 first2, InputIt2 last2)
{
    for (; first2 != last2; ++first1)
    {
        if (first1 == last1 || *first2 < *first1)
            return false;
        if ( !(*first1 < *first2) )
            ++first2;
    }
    return true;
}

所以*first1 > *first2导致算法返回false*first1 >= *first2导致firsts2递增,所以唯一递增的条件first2是什么时候*first1 == *first2那么为什么使用小于<和否定运算符运算符而不是像我的实现中那样!直接使用等于运算符呢?==

标签: c++algorithm

解决方案


该算法正在排序范围内工作。您需要一个<关系来对一系列元素进行排序,但不一定是一个==关系,因此使用<构成的限制更少并且更通用。


还要考虑大多数算法和容器使用<而不是==比较元素。参见例如std::map

在标准库使用比较要求的任何地方,唯一性都是通过使用等价关系确定的。用不精确的术语来说,如果两个对象 a 和 b 的比较都小于另一个:!comp(a, b) && !comp(b, a),则认为两个对象是等价的(不唯一的)。

映射中的两个键在!comp(a,b) && !comp(b,a). 大多数情况下,这与 相同a == b,但不一定。


推荐阅读