Mr M.
Mr M.

Reputation: 735

Smallest lexicographical value of a string

When comparing strings with operator <, what is the smallest string?

To be more specific, what is a string that is smaller (using <) than any other string?

Upvotes: 7

Views: 2446

Answers (1)

T.C.
T.C.

Reputation: 137425

The empty string is the "smallest" of all strings - that is, it compares less than any non-empty string.

§21.4.8.4 [string::op<]:

template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT,traits,Allocator>& lhs,
                const basic_string<charT,traits,Allocator>& rhs) noexcept;

1 Returns: lhs.compare(rhs) < 0.

§21.4.7.9 [string::compare]:

int compare(const basic_string& str) const noexcept;

1 Effects: Determines the effective length rlen of the strings to compare as the smallest of size() and str.size(). The function then compares the two strings by calling traits::compare(data(), str.data(), rlen).

2 Returns: The nonzero result if the result of the comparison is nonzero. Otherwise, returns a value as indicated in Table 72.

Table 72 — compare() results

 Condition               Return Value
 size() < str.size()     < 0
 size() == str.size()    0
 size() > str.size()     > 0

For any comparison between an empty string e and a non-empty string ne, rlen is zero, in which case traits::compare() is specified to return zero*. Hence, the result of e.compare(ne) is always less than zero per table 72, and e < ne is always true.


* The compare() function of character traits is specified to return zero if "for each i in [0,n), X::eq(p[i],q[i]) is true" (§21.2.1 [char.traits.require], Table 62); when n == 0, the range is empty, and the condition is vacuously true.

Upvotes: 11

Related Questions