String :: compare redundant parameter?

The following overload exists in the C ++ link to string::compare :

 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 0 (false) means equal lines). It's right? If not, can you give an example showing a specific case when the comparison is false if unequal lengths are compared ( n1 != n2 )?

Thanks!

+4
source share
3 answers

Parameters n1 and n2 are the maximum number of characters to compare. The std :: compare function will trim values ​​if they exceed the length of the strings. Here is an example when the values ​​are not 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 a specific case that you requested.

+1
source

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

The comparison is a three-digit comparison: negative / zero / positive are important types of return value, not just true / false. It returns int to false if the strings are equal, and not if they are not.

If you lexically arrange (under) strings of different lengths, compare will tell you in what order they come.

If everything you care about is tantamount (by), then different lengths mean not equal. As an optimization, you can skip the compare call if n1 != n2 .

+8
source

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 larger than the parameter string."

So this is just a lie or a lie. eg.

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

Operand: "abc", parameter: "declaration" Returns: +1

+1
source

All Articles