在c ++ 17中是否存在stl容器的三向比较

rtp*_*pax 2 c++ comparison c++17

是否有标准函数允许stl容器的三路比较

例如

cmp({1,2},{1,3}) < 0
cmp({1,2},{1,2}) == 0
Run Code Online (Sandbox Code Playgroud)

我想避免在一些可能的大型容器上进行两次比较,如果有标准的话,我宁愿使用标准功能而不是自己滚动.我没有在stl容器的cppreference页面上看到任何内容,但我希望有一些东西.

Bar*_*rry 7

是否有标准函数允许stl容器的三路比较

没有.C++ 20将添加std::lexicographical_compare_3way哪个依赖于operator<=>它带来的所有其他东西.

在那之前,实现这样做的算法相当简单,只需稍微修改一下std::lexicographical_compare:

template<class InputIt1, class InputIt2>
int compare_3way(InputIt1 first1, InputIt1 last1,
                 InputIt2 first2, InputIt2 last2)
{
    for ( ; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2 ) {
        if (*first1 < *first2) return -1;
        if (*first2 < *first1) return 1;
    }

    if (first1 == last1) {
        return (first2 == last2) ? 0 : -1;
    } else {
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

这仍然可能对每个元素进行两次比较.因此,这种简单实现的替代方法是传递另一个模板参数,该模板参数本身是一个返回一个的三向比较函数int,因此循环的主体将是:

int c = compare3way(*first1, *first2);
if (c != 0) {
    return c;
}
Run Code Online (Sandbox Code Playgroud)

默认实现可以回退到:

struct Compare3way {
    template <typename T, typename U>
    int operator()(T const& lhs, U const& rhs) const {
        if (lhs < rhs) return -1;
        if (rhs < lhs) return 1;
        return 0;
    }
};
Run Code Online (Sandbox Code Playgroud)