Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing String Elements vs Strings

Tags:

c++

string

The following code prints

1
0

And I've been wondering why the values are different if the comparisons are using the same string… I've been struggling with this for a while and cannot figure out why they return different boolean values.

int main()
{
    string stringArray[] = { "banana","Banana","zebra","apple","Apple","Zebra","cayote" };

    cout << (stringArray[1] < stringArray[0]) << endl;
    cout << ("Banana" < "banana") << endl;

    return 0;
}
like image 514
user126865 Avatar asked Oct 28 '15 16:10

user126865


Video Answer


1 Answers

stringArray[n] is an std::string, but "Banana" is a string literal (an array of chars).

When you do "Banana" < "banana", both string literals are implicitly converted to char pointers pointing to the char array. < then compares those memory addresses.

like image 82
emlai Avatar answered Oct 22 '22 23:10

emlai