字符串比较C ++中的怪异行为

时间:2019-03-24 18:36:48

标签: c++ string

我正在使用我尝试比较的标准std :: string变量。但是,很奇怪的是,我得到的结果很奇怪:

mappedTypes.Where(x => x.ReferenceId == new Guid("1a087b71-638c-4f3c-b1cf-3b0438c181c0"))
           .Select(x => (Guid?) x.MappingId)
           .FirstOrDefault();

我希望因为一个字符串比另一个字符串短,所以按顺序排列,对于“ 44” <“ 111”应该总是正确的。

整个代码如下:

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

并返回:

#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;
}

我正在Windows10上使用MinGW 16.1中的g ++(GCC)8.2.0。我在这里想念什么吗?如何强制它给我正确的结果(较短的字符串小于较长的字符串)。 谢谢。

1 个答案:

答案 0 :(得分:2)

bool smaller2 = "44" < "111";  // <- returns true, CORRECT

不。你只是变得笨拙。这是在比较字符串文字的地址,而不是与std :: string实例相同。实际上,您可以在代码中将该表达式替换为“ 111” <“ 44”,并且如果编译器按照声明的顺序将内存中的字符串对齐,它可能会返回true。

按字典顺序比较字符串的正确方法:

std::string str1 = "44";
std::string str2 = "111";
bool cmp1 = (str1 < str2);  // false, since '4' is greater than '1'

将字符串比较为整数的正确方法:

int val1 = std::stoi(str1);  // 44
int val2 = std::stoi(str2);  // 111
bool cmp2 = (val1 < val2);   // true since 44 is less than 111
相关问题