public static member function
<string>

std::char_traits::compare

static int compare (const char_type* p, const char_type* q, size_t n);
Compare sequences of characters
Compares the sequence of n characters pointed by p to the sequence of n characters pointed by q.

The function performs a lexicographical comparison where two characters are considered equal if member eq returns true, and one character is considered less than another one if member lt returns true.

For all character traits types, it shall behave as if defined as:
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;
}
Although the specific signature may vary.

Parameters

p, q
Pointers to arrays with a sequence of characters each.
Notice that the function will consider that the length of both sequences is n characters, independently on whether any of them contains or not null-characters.
Member type char_type is the character type (i.e., the class template parameter in char_traits).
n
Length (in characters) of the sequence of characters to compare.
size_t is an unsigned integral type.

Return Value

Returns a signed integral indicating the relation between the sequences:
valuerelation
0All characters compare equal
<0The first character that does not compare equal is less in p.
>0The first character that does not compare equal is greater in p.

Example

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;
}

Output:
foo and bar are equal


Complexity

Up to linear in n.

Exception safety

Unless either p or q does not point to an array long enough, this member function never throws exceptions (no-throw guarantee) in any of the standard specializations.
Otherwise, it causes undefined behavior.

See also