作者:小菜鸡 | 来源:互联网 | 2022-12-07 16:39
是否有标准函数允许stl容器的三路比较
例如
cmp({1,2},{1,3}) <0
cmp({1,2},{1,2}) == 0
我想避免在一些可能的大型容器上进行两次比较,如果有标准的话,我宁愿使用标准功能而不是自己滚动.我没有在stl容器的cppreference页面上看到任何内容,但我希望有一些东西.
1> Barry..:
是否有标准函数允许stl容器的三路比较
没有.C++ 20将添加std::lexicographical_compare_3way
哪个依赖于operator<=>
它带来的所有其他东西.
在那之前,实现这样做的算法相当简单,只需稍微修改一下std::lexicographical_compare
:
template
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
int operator()(T const& lhs, U const& rhs) const {
if (lhs