简体   繁体   中英

String comparison using general comparators

I am trying to see what happens when we compare strings directly using operators like <, >, etc. The two usages in the code below surprisingly give different answers. Aren't they exactly same way of saying things?

#include <iostream>

template <class T>
T max(T a, T b)
{    
  //Usage 1:
  if (a > b) return a; else return b;

  //Usage 2:
  return a > b ? a : b ;
}

int main()
{
  std::cout << "max(\"Alladin\", \"Jasmine\") = " << max("Alladin", "Jasmine") << std::endl ;
}

Usage 1 gives "Jasmine" while usage 2 gives "Alladin".

When you use:

max("Alladin", "Jasmine")

it is equivalent to using:

max<char const*>("Alladin", "Jasmine")

In the function, you end up comparing pointers. The outcome of the call will depend on the values of the pointers. It is not guaranteed to be predictable.

Perhaps you want to use:

max(std::string("Alladin"), std::string("Jasmine"))

or

max<std::string>("Alladin", "Jasmine")

Be warned that some compiler might pick up std::max when you use that. You may want to change max to my_max or something like that.

Both methods are wrong. Character strings don't have valid > operator.

You can compare std::string instead:

#include <iostream>
#include <string>

template <class T>
T my_max(T a, T b)
{
    return a > b ? a : b;
}

int main()
{
    std::string a = "Alladin";
    std::string b = "Jasmine";
    std::cout << "my max: " << my_max(a, b) << std::endl;

    //standard max function:
    std::cout << "standard max: " << max(a, b) << std::endl;
}

The expected result should always be "Jasmine"

You are not actually comparing the string in your code. "Alladin" and "Jasmine" are actually of the type const char[] and they decay into pointers when you call max("Alladin", "Jasmine") . This means that in your function you are comparing the address of the strings and not the contents.

If you meant to test std::string s then you need to create std::string s and pass them to your max function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM