Reputation: 226
I am using standard std::string variables which I try to compare. Quite strangely however, I am getting weird results:
string str1 = "44", str2 = "111";
bool smaller1 = str1.compare(str2) > 0; // <- returns true, although should be false
bool smaller2 = "44" < "111"; // <- returns true, CORRECT
string str3(2, '4'), str4(3, '1');
bool small3 = str3 < str4; // <- returns false, although should be true
I would expect since one string is shorter than the other, the lexacographical ordering should always give me true for "44" < "111".
The whole code looks like:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "44", str2 = "111";
string str3(2, '4'), str4(3, '1');
bool cmp1 = str1 < str2,
cmp2 = "44" < "111",
cmp3 = str3 < str4,
cmp4 = str3.compare(str4) < 0;
std::cout << "1: " << cmp1 << "\n";
std::cout << "2: " << cmp2 << "\n";
std::cout << "3: " << cmp3 << "\n";
std::cout << "4: " << cmp4 << "\n";
return 0;
}
and returns:
1: 0
2: 1
3: 0
4: 0
I am using g++ (GCC) 8.2.0 from MinGW 16.1 on Windows10. Am I missing something here? How can I force it to give me the correct results (shorter strings are smaller than longer). Thanks.
Upvotes: 1
Views: 384
Reputation: 104474
bool smaller2 = "44" < "111"; // <- returns true, CORRECT
No. You're just getting lukcy. That's comparing the addresses of string literals, not the same thing as an instance of an std::string. As a matter of fact, you could replace that expression in your code as "111" < "44" and it will likely return true if the compiler aligns the strings in memory in the same order as declared.
Correct way to compare strings lexicographical:
std::string str1 = "44";
std::string str2 = "111";
bool cmp1 = (str1 < str2); // false, since '4' is greater than '1'
Correct way to compare strings as integers:
int val1 = std::stoi(str1); // 44
int val2 = std::stoi(str2); // 111
bool cmp2 = (val1 < val2); // true since 44 is less than 111
Upvotes: 1