std::string_view compare() method
- od C++17
// (1) Const version only
constexpr int compare( basic_string_view v ) const noexcept;
// (2) Const version only
constexpr int compare( size_type pos1, size_type count1,
basic_string_view v ) const;
// (3) Const version only
constexpr int compare( size_type pos1, size_type count1, basic_string_view v,
size_type pos2, size_type count2 ) const;
// (4) Const version only
constexpr int compare( const CharT* s ) const;
// (5) Const version only
constexpr int compare( const CharT* s ) const;
constexpr int compare( size_type pos1, size_type count1,
const CharT* s ) const;
// (6) Const version only
constexpr int compare( size_type pos1, size_type count1,
const CharT* s, size_type count2 ) const;
Compares two character sequences.
-
(1) The length
rlen
of the sequences to compare isstd::min(size(), v.size())
.
The function compares the two views by callingTraits::compare(data(), v.data(), rlen)
, and returns a value according to the following table:importantThis section requires improvement. You can help by editing this doc page.
-
(2) Equivalent to
substr(pos1, count1).compare(v)
. -
(3) Equivalent to
substr(pos1, count1).compare(v.substr(pos2, count2))
. -
(4) Equivalent to
compare(basic_string_view(s))
. -
(5) Equivalent to
substr(pos1, count1).compare(basic_string_view(s))
. -
(6) Equivalent to
substr(pos1, count1).compare(basic_string_view(s, count2))
.
Parameters
v
- view to compares
- pointer to the character string to compare tocount1
- number of characters of this view to comparepos1
- position of the first character in this view to comparecount2
- number of characters of the given view to comparepos2
- position of the first character of the given view to compare
Returns value
- Negative value if
*this
appears before the character sequence specified by the arguments, in lexicographical order. - Zero if both character sequences compare equivalent.
- Positive value if
*this
appears after the character sequence specified by the arguments, in lexicographical order.
Complexity
This section requires improvement. You can help by editing this doc page.
Exceptions
(none)
Possible implementation
template<class CharT, class Traits, class Alloc>
int basic_string_view<CharT, Traits, Alloc>::compare(std::basic_string_view s) const noexcept
{
size_type lhs_sz = size();
size_type rhs_sz = s.size();
int result = traits_type::compare(data(), s.data(), std::min(lhs_sz, rhs_sz));
if (result != 0)
return result;
if (lhs_sz < rhs_sz)
return -1;
if (lhs_sz > rhs_sz)
return 1;
return 0;
}
Example
#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 );
}
Hover to see the original license.