gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:17:25 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com