Comparing strings lexicographically

Comparing std::string -s like that will work. However you are comparing string literals. To do the comparison you want either initialize a std::string with them or use strcmp:

if(std::string("aa") > std::string("bz")) cout<<"Yes";

This is the c++ style solution to that.

Or alternatively:

if(strcmp("aa", "bz") > 0) cout<<"Yes";

EDIT(thanks to Konrad Rudolph’s comment): in fact in the first version only one of the operands should be converted explicitly so:

if(std::string("aa") > "bz") cout<<"Yes";

Will again work as expected.

EDIT(thanks to churill’s comment): since c++14 you can use string literals:

if("aa"s > "bz") cout<<"Yes";

Leave a Comment