![](/img/trans.png)
[英]Standard way to create a const set with the value as a union/intersection of two sets in C++?
[英]Does C++ have a standard way to do a tristate comparison of two std::sets, vectors, etc?
是否有等效於std :: string :: compare的其他std類型,例如std :: set? 我正在尋找一種內置算法,該算法只能進行一次比較,並分別給出小於,等於或大於-1、0、1之類的值。
沒有,沒有單一的算法可以做到這一點。 但是您可以使用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;
}
}
您可以編寫(僅使用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;
}
標准庫中沒有通用的三向比較功能,因此您需要自己實現。 使用小於運算符實現它很簡單。
也沒有使用“三向比較”功能的標准算法(從C繼承的算法無論如何都不能與容器一起使用)。
有人建議在標准中添加一個新的運算符,以實現這種比較。
C ++ 2a引入了宇宙飛船運算符( <=>
),該運算符主要用於此操作。 (參見http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf )
在此之前,您必須依靠其他方式作為建議的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.