std::lexicographical_compare_three_way
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
template< class InputIt1, class InputIt2, class Cmp > constexpr auto lexicographical_compare_three_way |
(1) | (C++20 起) |
template< class InputIt1, class InputIt2 > constexpr auto lexicographical_compare_three_way |
(2) | (C++20 起) |
使用三路比較詞典式地比較兩個範圍 [
first1,
last1)
和 [
first2,
last2)
,併產生最強適用比較類別型別的結果。
1) 如果存在,返回兩個範圍內第一個不相等元素對根據 comp 的順序,否則(如果一個範圍根據 comp 等效於另一個範圍的字首),返回兩個範圍長度的順序。
2) 等效於 return std::lexicographical_compare_three_way(
first1, last1, first2, last2, std::compare_three_way());
first1, last1, first2, last2, std::compare_three_way());
如果返回型別不是三種比較類別型別之一,則程式格式錯誤。
目錄 |
[編輯] 引數
first1, last1 | - | 定義要檢查的第一個元素範圍的迭代器對 |
first2, last2 | - | 定義要檢查的第二個元素範圍的迭代器對 |
comp | - | 函式物件 |
型別要求 | ||
-InputIt1, InputIt2 必須滿足 LegacyInputIterator 的要求。 |
[編輯] 返回值
上面指定的比較類別型別的值。
[編輯] 複雜度
給定 N1 為 std::distance(first1, last1),N2 為 std::distance(first2, last2)
1) 最多 min(1,N2) 次 comp 呼叫。
[編輯] 可能的實現
template<class I1, class I2, class Cmp> constexpr auto lexicographical_compare_three_way(I1 f1, I1 l1, I2 f2, I2 l2, Cmp comp) -> decltype(comp(*f1, *f2)) { using ret_t = decltype(comp(*f1, *f2)); static_assert(std::disjunction_v< std::is_same<ret_t, std::strong_ordering>, std::is_same<ret_t, std::weak_ordering>, std::is_same<ret_t, std::partial_ordering>>, "The return type must be a comparison category type."); bool exhaust1 = (f1 == l1); bool exhaust2 = (f2 == l2); for (; !exhaust1 && !exhaust2; exhaust1 = (++f1 == l1), exhaust2 = (++f2 == l2)) if (auto c = comp(*f1, *f2); c != 0) return c; return !exhaust1 ? std::strong_ordering::greater: !exhaust2 ? std::strong_ordering::less: std::strong_ordering::equal; } |
[編輯] 示例
執行此程式碼
#include <algorithm> #include <cctype> #include <compare> #include <iomanip> #include <iostream> #include <string_view> #include <utility> using namespace std::literals; void show_result(std::string_view s1, std::string_view s2, std::strong_ordering o) { std::cout << std::quoted(s1) << " is "; std::is_lt(o) ? std::cout << "less than ": std::is_gt(o) ? std::cout << "greater than ": std::cout << "equal to "; std::cout << std::quoted(s2) << '\n'; } std::strong_ordering cmp_icase(unsigned char x, unsigned char y) { return std::toupper(x) <=> std::toupper(y); }; int main() { for (const auto& [s1, s2] : { std::pair{"one"sv, "ONE"sv}, {"two"sv, "four"sv}, {"three"sv, "two"sv} }) { const auto res = std::lexicographical_compare_three_way( s1.cbegin(), s1.cend(), s2.cbegin(), s2.cend(), cmp_icase); show_result(s1, s2, res); } }
輸出
"one" is equal to "ONE" "two" is greater than "four" "three" is less than "two"
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3410 | C++20 | 要求迭代器之間進行多餘的比較 | 該要求已移除 |
[編輯] 另請參閱
如果一個範圍在字典上小於另一個範圍,則返回 true (函式模板) | |
(C++20) |
實現 x <=> y 的受限函式物件 (類) |
如果一個範圍在字典上小於另一個範圍,則返回 true (演算法函式物件) |