c++ - s.compare 成员函数在下面的 C++ 代码中的行为如何?

标签 c++ string

我有下面这个 C++ 代码来解决作业,在我用 Code::Blocks 运行它之后,它告诉我 i=0,这意味着表达式 s.compare(t)<0是假的。但是,在我看来,情况恰恰相反:( s<t ,因为 AbcA < AAbcA )。有人可以给我解释一下吗?

#include <iostream>
#include <string>

using namespace std;

int main(void) {
        string s = "Abc", t = "A";
        s=s+t;
        t=t+s;
        int i = s.compare(t)<0;
        int j = s.length()<t.length();
        cout<<i+j<<endl;
        return 0;
}

最佳答案

根据引用std::string::compare返回:

negative value if *this appears before the character sequence specified by the arguments, in lexicographical order

zero if both character sequences compare equivalent

positive value if *this appears after the character sequence specified by the arguments, in lexicographical order

Lexicographical comparison被定义为:

Lexicographical comparison is a operation with the following properties:

  • Two ranges are compared element by element. The first mismatching element defines which range is lexicographically less or greater than the other.
  • If one range is a prefix of another, the shorter range is lexicographically less than the other.
  • If two ranges have equivalent elements and are of the same length, then the ranges are lexicographically equal.
  • An empty range is lexicographically less than any non-empty range.
  • Two empty ranges are lexicographically equal.

"AbcA" 按字典顺序出现在 "AAbc" 之后,因为第一个非等号字符 'b' ( ASCII 0x62) 'A' (ASCII 0x41)

关于c++ - s.compare 成员函数在下面的 C++ 代码中的行为如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218924/

相关文章:

c++ - 使用 C++ 库 GLEW 在 openGl 中绘制一个红色三角形

c++ - 我可以在 C++ 程序之外使用随机内存地址访问随机数据吗

c++ - 从 map 中删除时出现奇怪的段错误

c++ - 无法解析包含空字符的字符串

Android 如何从字符串中删除(“)字符

c - 扩展字符串而不连接

c++ - vector 的最小值显示为 0

c++ - 找到相对于任意原点的两点之间的顺时针角度

string - 从字节缓冲区传输到 AnsiString 时丢失数据

.net - .Net 中的 struct String 会有好处吗?