c++ - C++ std::string::compare() 与字符串运算符之间的不一致

标签 c++ string compare

给定下面的一段 C++ 代码

cout<<("100">"035")<<"\n";
cout<<("100"<"035")<<"\n";
string str = "100";
cout<<str.compare("035");

这段代码的输出是

0
1
1

这意味着运算符(operator)“100”<“035”但比较功能“100”>“035”。这两者有任何已知的实现差异吗?

附言“100” > “035” 绝对更有意义。

最佳答案

C 字符串字面量(例如 "100")将自身作为指针进行比较。

std::string comparison compare content lexicography.

如果您想要一致的结果:

using namespace std::string_literals;
std::cout << ("100"s > "035"s)<<"\n";
std::cout << ("100"s < "035"s)<<"\n";
std::string str = "100"s;
std::cout << str.compare("035");

“100”s“等同于”std::string("100")

关于c++ - C++ std::string::compare() 与字符串运算符之间的不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61300156/

相关文章:

c++ - 基于范围的for循环的range_declaration中各个说明符之间的性能差异

PHP,str_pad unicode 问题

python - Python 中的增量函数名称

C++ 字符串比较未按预期工作

c++ - 如何卡住一个变量,因为它第一次分配?

c++ - 启动时在 ros2 中找不到共享运行时库

c++ - 使用 make 构建时在 C++ 文件中泛化 include 语句

c - 在字符串 C 中搜索字符串的函数

c++ - 我如何比较 std::map 的正文成员?

c - 比较两个应该相同的单词时 strcmp 失败