std::string::compare() returns an int
:
s
and t
are equal,s
is less than t
,s
is greater than t
.If you want your first code snippet to be equivalent to the second one, it should actually read:
if (!s.compare(t)) {
// 's' and 't' are equal.
}
The equality operator only tests for equality (hence its name) and returns a bool
.
To elaborate on the use cases, compare()
can be useful if you're interested in how the two strings relate to one another (less or greater) when they happen to be different. PlasmaHH rightfully mentions trees, and it could also be, say, a string insertion algorithm that aims to keep the container sorted, a dichotomic search algorithm for the aforementioned container, and so on.
EDIT: As Steve Jessop points out in the comments, compare()
is most useful for quick sort and binary search algorithms. Natural sorts and dichotomic searches can be implemented with only std::less.