为什么 str.length() 输出为字符?
Why str.length() is output as a char?
这是我的 C++ 代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str1;
cin>>str1;
int j=-1;
cout<<typeid(str1.length()).name()<<endl;
cout<<(j>str1.length())<<endl;
int len=str1.length();
cout<<len<<' '<<(j>=len);
}
我输入:
abc
结果是:
j
1
3 0
可以看出,typeid(str1.length()).name()
是j
,而-1>str1.length()
不知道为什么会这样
I wonder why this is the case
typeid(str1.length()).name()
is j
因为这就是您的语言实现碰巧破坏类型名称的方式。在我的系统上是 m.
要清楚,该类型与 std::size_t
相同,后者是无符号整数类型的别名。
and -1>str1.length()
这是因为-1是一个负数,超出了无符号类型的可表示值,当转换为可表示范围时,它变得大于3。实际上,-1转换为无符号将是该类型的最大可表示值。
str1.length()
的类型是std::string::size_type
,是一些无符号整数类型(通常是size_t
)。在比较 j>str1.length()
中,有符号整数 j
被转换为无符号类型模 2^n
对于某些 n
,因此 -1
变为 2^n-1
-一个很大的正值。
这是我的 C++ 代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str1;
cin>>str1;
int j=-1;
cout<<typeid(str1.length()).name()<<endl;
cout<<(j>str1.length())<<endl;
int len=str1.length();
cout<<len<<' '<<(j>=len);
}
我输入:
abc
结果是:
j
1
3 0
可以看出,typeid(str1.length()).name()
是j
,而-1>str1.length()
不知道为什么会这样
I wonder why this is the case
typeid(str1.length()).name()
is j
因为这就是您的语言实现碰巧破坏类型名称的方式。在我的系统上是 m.
要清楚,该类型与 std::size_t
相同,后者是无符号整数类型的别名。
and -1>str1.length()
这是因为-1是一个负数,超出了无符号类型的可表示值,当转换为可表示范围时,它变得大于3。实际上,-1转换为无符号将是该类型的最大可表示值。
str1.length()
的类型是std::string::size_type
,是一些无符号整数类型(通常是size_t
)。在比较 j>str1.length()
中,有符号整数 j
被转换为无符号类型模 2^n
对于某些 n
,因此 -1
变为 2^n-1
-一个很大的正值。