Search code examples
c++stringinfinite

Is it possible to construct an "infinite" string?


Is there any real sequence of characters that always compares greater than any other string?

My first thought was that a string constructed like so:

std::basic_string<T>(std::string::max_size(), std::numeric_limits<T>::max())

Would do the trick, provided that the fact that it would almost definitely fail to work isn't such a big issue. So I presume this kind of hackery could only be accomplished in Unicode, if it can be accomplished at all. I've never heard of anything that would indicate that it really is possible, but neither have I heard tell that it isn't, and I'm curious.

Any thoughts on how to achieve this without a possibly_infinite<basic_string<T>>?


Solution

  • I assume that you compare strings using their character value. I.e. one character acts like a digit, a longer string is greater than shorter string, etc.

    s there any real sequence of characters that always compares greater than any other string?

    No, because:

    1. Let's assume there is a string s that is always greater than any other string.
    2. If you make a copy of s, the copy will be equal to s. Equal means "not greater". Therefore there can be a string that is not greater than s.
    3. If you make a copy of s and append one character at the end, it will be greater than original s. Therefore there can be a string that is greater than s.
    4. Which means, it is not possible to make s.

    I.e.

    A string s that is always greater than any other string cannot exist. A copy of s (copy == other string) will be equal to s, and "equal" means "not greater".
    A string s that is always greater or equal to any other string, can exist if a maximum string size has a reasonable limit. Without a size limit, it will be possible to take a copy of s, append one character at the end, and get a string that is greater than s.

    In my opinion, the proper solution would be to introduce some kind of special string object that represents infinitely "large" string, and write a comparison operator for that object and standard string. Also, in this case you may need custom string class.

    It is possible to make string that is always less or equal to any other string. Zero length string will be exactly that - always smaller than anything else, and equal to other zero-length strings.

    Or you could write counter-intuitive comparison routine where shorter string is greater than longer string, but in this case next code maintainer will hate you, so it is not a good idea.

    Not sure why would you ever need something like that, though.