是否有一个标准函数允许对 STL 容器进行三向比较
例如
cmp({1,2},{1,3}) < 0
cmp({1,2},{1,2}) == 0
我想避免对一些可能比较大的容器进行两次比较,如果有一些标准的话,我宁愿使用标准函数也不愿自己动手。我没有在 STL 容器的 cppreference 页面上看到任何东西,但我希望有一些东西。
最佳答案
Is there a standard function that allows three way comparison of stl containers
没有。 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;
}
}
这仍然可能对每个元素进行两次比较。因此,这种简单实现的替代方法是传递另一个模板参数,该参数本身是一个返回 int
的三向比较函数。 ,这样循环体就是:
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;
}
};
关于c++ - c++17 中的 STL 容器是否有三向比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51861467/