我有下面这个 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 orderzero 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/