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?
The lexicographically smallest string is “abcde”.
The smallest lexicographical order is an order relation where string s is smaller than t, given the first character of s (s1) is smaller than the first character of t (t1), or in case they are equivalent, the second character, etc.
Explanation: 0345989723478563548 is the lexicographical smallest possible number.
Approach: In order to get the lexicographically smallest string, we need to take the minimum character from the first K characters every time we choose a character from str. To do that, we can put the first K characters in a priority_queue (min-heap) and then choose the smallest character and append it to X.
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 ofsize()
andstr.size()
. The function then compares the two strings by callingtraits::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With