sing
sing

Reputation: 11

How are strings compared in IF statement arguments

In the if function argument, how is the string s and t compared? Why is the condition (s > t) true?

string s = "to be";
string t = "not " + s;              // t = “not to be”
string u = s + " or " + t;          // u = “to be or not to be”
if (s > t)                          // true: “to be” > “not to be”
cout << u;                          // outputs “to be or not to be”

Upvotes: 1

Views: 74

Answers (2)

bolov
bolov

Reputation: 75727

std::string operator comp

All comparisons are done via the compare() member function (which itself is defined in terms of Traits::compare()):

  • Two strings are equal if both the size of lhs and rhs are equal and each character in lhs has equivalent character in rhs at the same position.
  • The ordering comparisons are done lexicographically -- the comparison is performed by a function equivalent to std::lexicographical_compare or std::lexicographical_compare_three_way (since C++20).

So, in short it does a lexicographical compare

I.e. "to be"s > "not to be"s == true because - at first position - 't' > 'n'.

Upvotes: 2

JaMiT
JaMiT

Reputation: 16873

The comparison of std::string was designed to be not surprising, or at least minimally surprising. If you stick to lowercase letters and spaces, as in your example, operator< and operator> follow alphabetical ordering.

  • not to be
  • to be
  • to be or not to be

Since you are sticking to the simple case, string{"to be"} > string{"not to be"} because they are in reverse alphabetical order. That is, 't' > 'n' (as characters).

When you expand into other characters, there might be some surprises. For example, 'Z' < 'a' since ASCII puts capital letters before lowercase letters. Still, the principle still holds: the ordering of std::string is based on the ordering of the underlying character set. Look for the first character position where the strings differ; the strings are ordered the same as the characters in that position. If one (and only one) string ran out of characters before a difference was found, then the shorter string comes before the longer one.

Upvotes: 1

Related Questions