我试图了解C ++字符串上的“ <”运算符,并尝试了一些测试用例。我意识到我认为应该表现相同的两个代码给出了不同的结果。以下是代码,这是什么原因?
string s="test";
string k="tes";
cout<<(s<k)<<endl; //returns false so it prints 0
cout<<("test"<"tes")<<endl; // returns true so it prints 1
我试图了解C ++字符串上的“ <”运算符,并尝试了一些测试用例。我意识到我认为应该表现相同的两个代码给出了不同的结果。以下是代码,这是什么原因?
string s="test";
string k="tes";
cout<<(s<k)<<endl; //returns false so it prints 0
cout<<("test"<"tes")<<endl; // returns true so it prints 1
s
andk
arestring
objects for which a comparison operator has been defined and performs what you expect."test"
and"tes"
are pointers to char that hold the address of the locations where these characters are stored. Thus the comparison is on the addresses.(s < k)
compares the values of the strings as you would expect.("test" < "tes")
compares the pointers to the beginning of the string literals as the compiler decides to arrange them in memory. Therefore, this comparison may return 0 or 1 depending on the compiler and settings in use, and both results are correct. The comparison is effectively meaningless.The "C way" to compare these string literals would be
strcmp("test", "tes")
.