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

来自cppreference.com
 
 
 
 
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 起)

比较两个字符序列。

1) 要比较的序列长度 rlensize()v.size() 的较小者。该函数通过调用 traits::compare(data(), v.data(), rlen) 比较两个视图,并根据下表返回一个值:
条件结果返回值
Traits::compare(data(), v.data(), rlen) < 0*this 小于 v<0
Traits::compare(data(), v.data(), rlen) == 0size() < v.size()*this小于 v<0
size() == v.size()*this 等于 v0
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);
}

[编辑] 参阅

比较两个字符串
(std::basic_string<CharT,Traits,Allocator> 的公开成员函数) [编辑]
(C++20 移除)(C++20 移除)(C++20 移除)(C++20 移除)(C++20 移除)(C++20)
以字典序比较两个字符串视图
(函数模板) [编辑]