public static member function
<string>

std::char_traits::compare

static int compare (const char_type* p, const char_type* q, size_t n);
比較字元序列
比較由p指向的n個字元的序列與由q指向的n個字元的序列。

該函式執行字典序比較,其中如果成員eq返回,則認為兩個字元相等true,如果成員lt返回,則認為一個字元小於另一個字元true.

對於所有字元特徵型別,其行為應類似於定義為
1
2
3
4
static int compare (const char_type* p, const char_type* q, size_t n) {
  while (n--) {if (!eq(*p,*q)) return lt(*p,*q)?-1:1; ++p; ++q;}
  return 0;
}
儘管具體簽名可能有所不同。

引數

p, q
指向每個具有字元序列的陣列的指標。
請注意,該函式將認為兩個序列的長度均為n個字元,而不管其中任何一個是否包含空字元。
成員型別char_type字元型別(即,char_traits 中的類模板引數)。
n
要比較的字元序列的長度(以字元為單位)。
size_t 是一個無符號整數型別。

返回值

返回一個有符號整數,指示序列之間的關係
relation
0所有字元的比較結果相等
<0第一個比較結果不相等的字元在p中較小。
>0第一個比較結果不相等的字元在p中較大。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// char_traits::compare
#include <iostream>   // std::cout
#include <string>     // std::basic_string, std::char_traits
#include <cctype>     // std::tolower
#include <cstddef>    // std::size_t

// case-insensitive traits:
struct custom_traits: std::char_traits<char> {
  static bool eq (char c, char d) { return std::tolower(c)==std::tolower(d); }
  static bool lt (char c, char d) { return std::tolower(c)<std::tolower(d); }
  static int compare (const char* p, const char* q, std::size_t n) {
    while (n--) {if (!eq(*p,*q)) return lt(*p,*q)?-1:1; ++p; ++q;}
    return 0;
  }
};

int main ()
{
  std::basic_string<char,custom_traits> foo,bar;
  foo = "Test";
  bar = "test";
  if (foo==bar) std::cout << "foo and bar are equal\n";
  return 0;
}

輸出
foo and bar are equal


複雜度

直到n的線性時間。

異常安全

除非pq未指向足夠長的陣列,否則此成員函式在任何標準專門化中都不會引發異常(無throw保證)。
否則,將導致未定義行為

另見