C++ 是否有标准方法对两个 std::sets、向量等进行三态比较?
Does C++ have a standard way to do a tristate comparison of two std::sets, vectors, etc?
对于其他 std 类型,例如 std::set,是否有等同于 std::string::compare 的东西?我正在寻找一种内置算法,它可以只进行一次比较,并分别为小于、等于、大于提供类似 -1、0、1 的值。
你可以这样写(仅使用 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;
}
不,没有一种算法可以做到这一点。但是您可以使用 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;
}
}
标准库中没有通用的三路比较函数,需要自己实现。使用小于运算符实现它很简单。
也没有使用 "three-way comparison" 函数的标准算法(从 C 继承的那些无论如何都不能与容器一起使用的算法除外)。
有一个 proposal 可以在标准中添加一个新的运算符来实现这种比较。
C++2a 引入了宇宙飞船运算符 (<=>
),主要用于此操作。 (参见 http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf)
在此之前,您必须依靠其他方式作为建议的答案。
对于其他 std 类型,例如 std::set,是否有等同于 std::string::compare 的东西?我正在寻找一种内置算法,它可以只进行一次比较,并分别为小于、等于、大于提供类似 -1、0、1 的值。
你可以这样写(仅使用 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;
}
不,没有一种算法可以做到这一点。但是您可以使用 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;
}
}
标准库中没有通用的三路比较函数,需要自己实现。使用小于运算符实现它很简单。
也没有使用 "three-way comparison" 函数的标准算法(从 C 继承的那些无论如何都不能与容器一起使用的算法除外)。
有一个 proposal 可以在标准中添加一个新的运算符来实现这种比较。
C++2a 引入了宇宙飞船运算符 (<=>
),主要用于此操作。 (参见 http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf)
在此之前,您必须依靠其他方式作为建议的答案。