std::basic_string_view<CharT,Traits>::compare
来自 zh.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 起) |
比较两个字符序列。
1) 要比较的序列的长度
rlen 取 size() 和 v.size() 中的较小值。该函数通过调用 traits::compare(data(), v.data(), rlen) 来比较两个视图,并根据下表返回值:| 条件 | 结果 | 返回值 | |
|---|---|---|---|
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); }
参见
|
比较两个字符串
(
std::basic_string<CharT,Traits,Allocator>
的公开成员函数)
|
|
|
(C++17)
(removed in C++20)
(removed in C++20)
(removed in C++20)
(removed in C++20)
(removed in C++20)
(C++20)
|
按字典序比较两个字符串视图
(函数模板) |