Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smallest lexicographical value of a string

Tags:

c++

string

c++11

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?

like image 918
Mr M. Avatar asked Oct 13 '14 15:10

Mr M.


People also ask

What is smallest lexicographical order in string?

The lexicographically smallest string is “abcde”.

What is lexicographically smallest?

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.

What is lexicographically smaller number?

Explanation: 0345989723478563548 is the lexicographical smallest possible number.

How do you find the lexicographically smallest character?

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.


1 Answers

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.

like image 175
T.C. Avatar answered Sep 23 '22 17:09

T.C.