std:: lexicographical_compare_three_way
|
ヘッダーで定義
<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以降) |
2つの範囲
[
first1
,
last1
)
と
[
first2
,
last2
)
を辞書順で比較し、三方比較を使用して適用可能な最も強い比較カテゴリ型の結果を生成します。
first1, last1, first2, last2, std:: compare_three_way ( ) ) ; と等価
戻り値の型が3つの比較カテゴリ型のいずれでもない場合、プログラムは不適格です:
目次 |
パラメータ
| first1, last1 | - | 検査対象の最初の要素範囲を定義するイテレータのペア |
| first2, last2 | - | 検査対象の2番目の要素範囲を定義するイテレータのペア |
| comp | - | 関数オブジェクト |
| 型要件 | ||
-
InputIt1, InputIt2
は
LegacyInputIterator
の要件を満たさなければならない。
|
||
戻り値
上記で指定された比較カテゴリ型の値。
計算量
\(\scriptsize N_1\) N 1 を std:: distance ( first1, last1 ) として、 \(\scriptsize N_2\) N 2 を std:: distance ( first2, last2 ) として定義する:
実装例
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>>, "戻り値の型は比較カテゴリ型でなければなりません。"); 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++規格に対して遡及的に適用されました。
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 3410 | C++20 | イテレータ間の不要な比較が要求されていた | その要求が削除された |
関連項目
|
ある範囲が別の範囲より辞書順で小さい場合に
true
を返す
(関数テンプレート) |
|
|
(C++20)
|
x
<=>
y
を実装する制約付き関数オブジェクト
(クラス) |
|
(C++20)
|
ある範囲が別の範囲より辞書順で小さい場合に
true
を返す
(アルゴリズム関数オブジェクト) |