Comparison between two strings

(This is part of the solution of Exercise 2.6 in Essential C++.)

I wrote a funtion to compare two value of int, double or string objects and return the max.

1
2
3
4
5
6
7
8
template<typename T>
T max2(T a, T b)
{
    if(a>b)
        return a;
    else
        return b;
}


I found some problem with comparison between two strings. If I call the function like this:

1
2
3
4
5
6
7
8
9
int main()
{
    cout<<max2("6.4","7.5")<<endl;
    
    string s1="6.4",s2="7.5";
    cout<<max2(s1,s2)<<endl;
    
    return 0;
}


the result will be:

6.4
7.5

The first statement returns the min.

But if I call the function like this:

1
2
3
4
5
6
7
8
9
int main()
{
    string s1="6.4",s2="7.5";
    cout<<max2(s1,s2)<<endl;
    
    cout<<max2("6.4","7.5")<<endl;
    
    return 0;
}


the result will be:

7.5
7.5

It's right.

I tried some times about the argument types ("6.4" or s1) and the order of these statement and found that these will influence the result. So why? Who can help me with this problem?
String literals are arrays of characters. When you pass them to max2 they will decay to pointers to the first element in the array, so you end up comparing pointers which is not what you want.

One way around this is to add an overload that handles const char* properly.

1
2
3
4
5
6
7
const char* max2(const char* a, const char* b)
{
    if (strcmp(a, b) > 0)
        return a;
    else
        return b;
}
@Peter87
Thanks!
I thought a string literal should always be a string object before. But if I didn't define a string object, it would not be.
I thought a string literal should always be a string object

Since C++11, you can say:
1
2
#include <string>
using namespace std::literals::string_literals;

After which, "foo" is an array of char, and
"bar"s (with the suffix s) is a std::string.

This way you can write max2("6.4"s ,"7.5"s) instead.

Since C++17, one would generally prefer std::string_view and its associated suffix sv.
Last edited on
mbozzi, thanks I didn't know that about string literal suffixes.
closed account (E0p9LyTq)
@Ganado,

operator ""s (C++14):
https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s

Please note there are three different ways to access the literal operators, not just one.

using namespace std::literals, using namespace std::string_literals, and using namespace std::literals::string_literals.


operator ""sv (C++17):
https://en.cppreference.com/w/cpp/string/basic_string_view/operator%22%22sv

The way to access the string_view literals is different.

using namespace std::literals, using namespace std::string_view_literals, and using namespace std::literals::string_view_literals.

You also get access if you say using namespace std, because std::literals is an inline namespace. The usual caveats apply.
Last edited on
@mbozzi
@FurryGuy
Thanks. I have learned about the string suffix.
Topic archived. No new replies allowed.