GeezerVison is showing cpprefjp.github.io — std::basic_string_view::compare - cpprefjp C++日本語リファレンス
最終更新日時:
2026年09月11日 13時06分31秒 (JST)
Akira Takahashi
が更新
履歴
編集
function
<string_view>
std:: basic_string_view:: compare (C++17)
constexpr int compare ( basic_string_view sv ) const noexcept ; // (1)
constexpr int compare ( size_type pos1 ,
size_type n1 ,
basic_string_view sv ) const ; // (2)
constexpr int compare ( size_type pos1 ,
size_type n1 ,
basic_string_view sv ,
size_type pos2 ,
size_type n2 ) const ; // (3)
constexpr int compare ( const CharT * s ) const ; // (4)
constexpr int compare ( size_type pos1 ,
size_type n1 ,
const CharT * s ) const ; // (5)
constexpr int compare ( size_type pos1 ,
size_type n1 ,
const CharT * s ,
size_type n2 ) const ; // (6)
概要
他の文字列との比較を行う。
(1) : *thisとsvを比較する
(2) : *thisの範囲[pos1, pos1 + n1)とsvを比較する
(3) : *thisの範囲[pos1, pos1 + n1)とsvの範囲[pos2, pos2 + n2)を比較する
(4) : *thisと文字配列sを比較する
(5) : *thisの範囲[pos1, pos1 + n1)と文字配列sを比較する
(6) : *thisの範囲[pos1, pos1 + n1)と文字配列sの先頭n2文字を比較する
効果
(1) :
size() とsv.size() のうち、小さい方をrlenとする
int result = Traits::compare (data() , sv.data() , rlen);
result != 0であればresultを返す。そうでなければ、以下のように返す:
size() < sv.size()であれば0未満の値を返す
size() == sv.size()であれば0を返す
size() > sv.size()であれば0超の値を返す
(2) : return substr (pos1, n1).compare(sv); と等価
(3) : return substr (pos1, n1).compare(sv.substr (pos2, n2)); と等価
(4) : return compare(basic_string_view(s)); と等価
(5) : return substr (pos1, n1).compare(basic_string_view(s)); と等価
(6) : return substr (pos1, n1).compare(basic_string_view(s, n2)); と等価
戻り値
*thisと比較対象が同値であれば値0を返す。そうでなければ非0を返す。*thisよりも比較対象がサイズもしくは辞書順として小さい場合は0未満の値、*thisよりも比較対象がサイズもしくは辞書順として大きい場合は0より大きい値を返す。
例外
計算量
例
#include <cassert>
#include <string_view>
int main ()
{
std::string_view a = "aaa" ;
std::string_view b = "bbb" ;
std::string_view c = "XXaaaYY" ;
// (1)
{
assert ( a . compare ( a ) == 0 );
assert ( a . compare ( b ) < 0 );
assert ( b . compare ( a ) > 0 );
}
// (2)
{
assert ( c . compare ( 2 , 3 , a ) == 0 );
}
// (3)
{
assert ( c . compare ( 2 , 3 , a , 0 , 3 ) == 0 );
}
// (4)
{
assert ( a . compare ( "aaa" ) == 0 );
}
// (5)
{
assert ( c . compare ( 2 , 3 , "aaa" ) == 0 );
}
// (6)
{
assert ( c . compare ( 2 , 3 , "aaaZZ" , 3 ) == 0 );
}
}
出力
バージョン
言語
処理系