[英]Does C++ have a standard way to do a tristate comparison of two std::sets, vectors, etc?
Is there an equivalent to std::string::compare for other std types, such as std::set? 是否有等效于std :: string :: compare的其他std类型,例如std :: set? I'm looking for a built-in algorithm that can do the comparison just once and give me something like -1, 0, 1 for less than, equal, greater than, respectively.
我正在寻找一种内置算法,该算法只能进行一次比较,并分别给出小于,等于或大于-1、0、1之类的值。
No there is no single algorithm which will do that. 没有,没有单一的算法可以做到这一点。 But you can compose such a function with the use of
std::mismatch
. 但是您可以使用
std::mismatch
组成这样的函数。
template<typename T1, typename T2>
int compare(T1 const& A, T2 const& B)
{
// find the first element which differs
auto mismatchPoint =
std::mismatch(std::begin(A), std::end(A), std::begin(B), std::end(B));
if (mismatchPoint.first == std::end(A)) {
// no elements differ
if (mismatchPoint.second == std::end(B))
return 0;
// A ends before B, so A < B
return -1;
} else if (mismatchPoint.second == std::end(B) {
// B ends before A, so B < A
return 1;
} else {
// compare the first different element
if (*mismatchPoint.first < *mismatchPoint.second)
return -1;
else
return 1;
}
}
You might write (using only operator <
): 您可以编写(仅使用
operator <
):
template <typename T>
int compare(const T& lhs, const T& rhs)
{
if (lhs < rhs) return -1;
else if (rhs < lhs) return 1;
else return 0;
}
There is no generic three way comparison function in the standard library, so you will need to implement it yourself. 标准库中没有通用的三向比较功能,因此您需要自己实现。 It's trivial to implement it using the less-than operator.
使用小于运算符实现它很简单。
There are also no standard algorithms that use a "three-way comparison" function (except those inherited from C that cannot be used with containers anyway). 也没有使用“三向比较”功能的标准算法(从C继承的算法无论如何都不能与容器一起使用)。
There is a proposal to add a new operator to the standard that would implement such comparison. 有人建议在标准中添加一个新的运算符,以实现这种比较。
C++2a introduces spaceship operator ( <=>
) which does mostly that. C ++ 2a引入了宇宙飞船运算符(
<=>
),该运算符主要用于此操作。 (See http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf ) (参见http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf )
Before that, you have to rely on other ways as proposed answers. 在此之前,您必须依靠其他方式作为建议的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.