Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 对于c+中的stl容器是否有三种方式的比较+;17_C++_Comparison_C++17 - Fatal编程技术网

C++ 对于c+中的stl容器是否有三种方式的比较+;17

C++ 对于c+中的stl容器是否有三种方式的比较+;17,c++,comparison,c++17,C++,Comparison,C++17,是否有允许stl容器进行三方比较的标准函数 乙二醇 cmp({1,2},{1,3})

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

乙二醇

cmp({1,2},{1,3})<0
cmp({1,2},{1,2})==0
我希望避免在一些可能较大的容器上进行两次比较,如果有标准的东西,我宁愿使用标准函数,也不愿使用自己的函数。我在CPPPreference页面上没有看到stl容器的任何内容,但我希望有一些东西

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

不,C++20将添加一个依赖于
操作符的函数,以及它带来的所有其他东西

在那之前,实现一个算法来实现这一点是相当简单的,只需稍微修改以下内容:

默认实现可以回退到以下位置:

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;
    }
};
struct Compare3way{
模板
int运算符()(T常量和lhs、U常量和rhs)常量{
如果(左侧<右侧)返回-1;
如果(rhs
C++20将获得“太空船操作员”(
)-我想这可能就是你想要的。@JesperJuhl是的,但不幸的是还没有C++20,所以我正在寻找C++17解决方案这正是我所期望的,谢谢你的确认。此外,您提供的示例3路比较非常好,值得注意的是,第一个示例可能是两个比较eachIt的
compare\u thire\u way
现在,尽管cppreference尚未更新
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;
    }
}
int c = compare3way(*first1, *first2);
if (c != 0) {
    return c;
}
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;
    }
};