Namespaces
Variants

std::basic_string_view<CharT,Traits>::compare

ja.cppreference.net より
 
 
 
 
constexpr int compare( basic_string_view v ) const noexcept;
(1) (C++17以降)
constexpr int compare( size_type pos1, size_type count1,
                       basic_string_view v ) const;
(2) (C++17以降)
constexpr int compare( size_type pos1, size_type count1, basic_string_view v,
                       size_type pos2, size_type count2 ) const;
(3) (C++17以降)
constexpr int compare( const CharT* s ) const;
(4) (C++17以降)
constexpr int compare( size_type pos1, size_type count1,
                       const CharT* s ) const;
(5) (C++17以降)
constexpr int compare( size_type pos1, size_type count1,
                       const CharT* s, size_type count2 ) const;
(6) (C++17以降)

2つの文字シーケンスを比較します。

1) 比較するシーケンスの長さ rlen は、size() と v.size() の小さい方です。この関数は traits::compare(data(), v.data(), rlen) を呼び出すことで2つのビューを比較し、以下の表に従って値を返します:
条件 結果 戻り値
Traits::compare(data(), v.data(), rlen) < 0 this が より小さい場合 v < 0
Traits::compare(data(), v.data(), rlen) == 0 size() < v.size() this が より小さい場合 v < 0
size() == v.size() this が 等しい場合 v 0
size() > v.size() this が より大きい場合 v > 0
Traits::compare(data(), v.data(), rlen) > 0 this が より大きい場合 v > 0
2) substr(pos1, count1).compare(v) と同等です。
3) substr(pos1, count1).compare(v.substr(pos2, count2)) と同等です。
4) compare(basic_string_view(s)) と同等です。
5) substr(pos1, count1).compare(basic_string_view(s)) と同等です。
6) substr(pos1, count1).compare(basic_string_view(s, count2)) と同等です。

パラメータ

v - 比較対象のビュー
s - 比較対象の文字列へのポインタ
count1 - このビューの比較対象文字数
pos1 - このビューで比較する最初の文字の位置
count2 - 指定されたビューの比較対象文字数
pos2 - 指定されたビューで比較する最初の文字の位置

戻り値

このビューが他の文字シーケンスより小さい場合は負の値、両方の文字シーケンスが等しい場合はゼロ、このビューが他の文字シーケンスより大きい場合は正の値。

計算量

1) 比較される文字数に対して線形。

例

#include <string_view>
int main()
{
    using std::operator""sv;
    static_assert("abc"sv.compare("abcd"sv) < 0);
    static_assert("abcd"sv.compare("abc"sv) > 0);
    static_assert("abc"sv.compare("abc"sv) == 0);
    static_assert(""sv.compare(""sv) == 0);
}

関連項目

2つの文字列を比較する
( std::basic_string<CharT,Traits,Allocator> のpublicメンバ関数)
(C++17) (C++20で削除) (C++20で削除) (C++20で削除) (C++20で削除) (C++20で削除) (C++20)
2つのstring viewを辞書順で比較する
(関数テンプレート)