为什么"test"在词典比较中排在"paul"之前
Why does "test" come before "paul" in lexicographical compare
我正在尝试排序字符串数组。我做了一些检查,发现了一些出乎我意料的东西。我无法解释。
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"}) { /* ... */ }
相关文章:
- 如何确保C++函数在定义之前声明(如override关键字)
- 为什么在定义函数之前先声明它
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 程序在执行程序的其余部分之前退出
- 如何将模板转换为C++11之前的模板
- '||'之前的预期主要表达
- (C++)为什么静态成员可以在初始化之前使用
- 标记 '","' 之前的预期主表达式
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- 错误:在"生成字符串"之前应为";"
- 为什么C++常量模板化向量在使用之前没有初始化?
- 类的前向声明之后的类成员函数定义,在类声明之前
- 'val' Arduino 错误代码之前的预期'('
- unique_ptr:在分配之前调用 reset 有什么效果
- 语句错误:"","标记之前有"预期的')'
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 编译 llvm 3.1 时,为什么会出现错误:在">"标记之前预期主表达式
- GStreamer在开始任何播放之前进行搜索
- 为什么"test"在词典比较中排在"paul"之前