Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string::compare superfluous parameter?

Tags:

c++

stl

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!

like image 398
rubenvb Avatar asked Dec 29 '22 04:12

rubenvb


2 Answers

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.

like image 126
Steve Jessop Avatar answered Dec 30 '22 18:12

Steve Jessop


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.

like image 31
Blastfurnace Avatar answered Dec 30 '22 16:12

Blastfurnace