0

I wanted to sort a vector of strings in terms of their ASCII order and my first try was using < > operators.I got some weird results and then I found compare function for strings in c++ and completed my task. But after that when I was reading c++ reference, It was written that > < operators are using the exact compare function for strings! So why do I get different results like this:

int main(){
    cout << ("ali" > "Zahra") << endl;
    string a = "ali";
    cout << a.compare("Zahra");
} 

the output is

0
461569

which means in the comparison with > operator "ali" comes first but with compare function "Zahra" comes first (which is more sensible because of ASCII).

So my question is how does these operators work for strings?

alilolo
  • 151
  • 1
  • 1
  • 9
  • @UnholySheep Yes. It compares the strings' characters in terms of their ASCII code starting from the index 0 character – alilolo Mar 19 '22 at 20:57
  • 1
    "Ali" and "Zahra" are pointers to strings. You are comparing pointers in the first case – Raildex Mar 19 '22 at 20:58

2 Answers2

5

The problem here is that there is no specialization for operator>(const char* lhs, const char* rhs) which is considering the lexicographic order. So in the first case:

"ali" > "Zahra"

is done through operator>(const void*, const void*) which compares memory addresses, not the content of the string.

To force using the lexicographic comparison you must use at least one std::string argument, eg: std::string("ali") > "Zahra, so that the proper overload will be chosen.

Jack
  • 131,802
  • 30
  • 241
  • 343
2

"ali" and string a = "ali"; are two ways to define a string value but have different types.

"ali" is a string literal, which the C++ standard defines as an array of n const char where n is the length of the string up to \0. This is commonly seen as const char[n]

string a = "ali"; type is explicitly defined with a type string (std::string) and the value ali.

So your first cout statement is calling operator> between two const char[n], and in the second cout statement, you are calling std::string::compare() and passing in a value of type const char[n]

And thus the results of two different function calls are not the same.

Alan
  • 45,915
  • 17
  • 113
  • 134