为什么"test"在词典比较中排在"paul"之前

Why does "test" come before "paul" in lexicographical compare

本文关键字:paul 之前 test 为什么 比较      更新时间:2023-10-16

我正在尝试排序字符串数组。我做了一些检查,发现了一些出乎我意料的东西。我无法解释。

if ("test" < "paul")
{
  cout << "test is less than paul" << endl;
}

为什么"test"小于"paul"?'p'的ASCII值低于't'。在字母表中,它也出现在p之前。在这两种情况下,字符串长度也相同。

我正在使用swap()按字母顺序对数组进行排序(我们正在尝试)。我不能使用sort(),我需要使用swap。

更新:在上面的例子中,我使用了指针,但这是我的实际代码。

DynamicArray<string> sectionName;  //declaration
swap(alreadySeen[i].sectionName[j],alreadySeen[i].sectionName[i]); //usage

这显然不是完整的代码,不要迷失在细节中

编译时总是启用警告。

 warning: comparison with string literal results in unspecified behavior [-Waddress]
     if ("test" < "paul")
                  ^~~~~~

你不是在比较字符串,而是在比较内存地址。这是一个魔杖盒的例子。

为了达到你想要的:

  • 如果需要使用c风格字符串,请使用std::strcmp:

    if(std::strcmp("test", "paul") < 0) { /* ... */ }
    
  • 如果你可以使用std::string,你可以简单地写:

    if(std::string{"test"} < std::string{"paul"}) { /* ... */ }