名稱空間
變體
操作

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) == 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)(在 C++20 中移除)(在 C++20 中移除)(在 C++20 中移除)(在 C++20 中移除)(在 C++20 中移除)(C++20)
按字典序比較兩個 string_view
(函式模板) [編輯]