4

In the C++ reference on string::compare, there is the following overload:

int compare ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 ) const; 

which has two parameters n1 and n2 which in my eyes should always be equal or the function returns an int equal to true (string::compare return value of 0 (false) signifies equal strings). Is this correct? If not, could you provide an example showing a specific case where the comparison would be false if unequal lengths (n1 != n2) are compared?

Thanks!

6
  • Wait, an int equal to false ? Commented Nov 20, 2010 at 15:48
  • @icecrime: an int can be easily converted to a bool, this is how you can use if with strcmp and the like for example. Commented Nov 20, 2010 at 16:01
  • Yes, but like strcmp, compare does not return a boolean value, but rather an integer (like it says). For equal strings compare returns an integer value of 0, which evaluates to false in boolean context. Commented Nov 20, 2010 at 16:05
  • @eq: ok, my mistake, but string equality can be tested by a.compare(b) nonetheless. Commented Nov 20, 2010 at 16:19
  • @ruvenb: just shaved such use from a code I was using this week, it certainly is not as clear as a == b, thus I really feel compare is better used when you actually care for ordering. Commented Nov 20, 2010 at 20:12

3 Answers 3

8

in my eyes should always be equal or the function returns an int equal to false

Compare is a tri-valued comparison: negative/zero/positive are the significant kinds of return value rather than just true/false. It returns an int equal to false if the strings are equal, not if they aren't.

If you're lexically ordering (sub)strings of different lengths, compare will tell you what order they come.

If all you care about is (sub)string equality, then different lengths implies not equal. As an optimization, you could skip calling compare if n1 != n2.

Sign up to request clarification or add additional context in comments.

Comments

1

The n1 and n2 parameters are the maximum number of characters to compare. The std::compare function will trim the values if they exceed the length of the strings. Here is an example where the values aren't equal and the function returns 0.

std::string a("AACAB"); std::string b("CAB"); std::cout << a.compare(2, 8, b, 0, 12) << '\n'; 

I'm not sure when this is useful but there is the specific case you asked for.

Comments

1

One documentation says: "Return Value: A negative value if the operand string is less than the parameter string; zero if the two strings are equal; or a positive value if the operand string is greater than the parameter string."

So its just not true or false. e.g.

Operand: "abc", Parameter: "ab" Returns: -1

Operand: "abc", Parameter: "ad" Returns: +1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.