[SOLVED] What is the logic behind "<" and ">" string operators in c++?

Issue

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?

Solution

"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.

Answered By – Alan

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *