(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;
elsereturn 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
constchar* max2(constchar* a, constchar* b)
{
if (strcmp(a, b) > 0)
return a;
elsereturn b;
}