C++ 中 string::size() 的奇怪行为当乘以负整数时
运行这段代码:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "Hello, world!";
cout << (-1)*a.size() << endl;
}
我得到:
18446744073709551603
这显然不是我想要的。每当我尝试将 string::size() 乘以负数(但不是正数!)时,都会发生这个恼人的错误。我不明白这里出了什么问题。
Running this code:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "Hello, world!";
cout << (-1)*a.size() << endl;
}
I get:
18446744073709551603
which is clearly not what I want. This annoying bug happens every time I try to multiply a string::size() by a negative number (but not for positive!). I can't figure out what is the problem here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
大小是无符号的。如果您想要负大小,则必须将其转换:
或在 64 位上:
请注意,对于高于
2,147,483,647
的大小(对于 64 位,9,223,372,036,854,775,807
)将产生错误的结果。size is unsigned. if you want negative size you have to cast it:
or on 64 bit:
beware that for sizes above
2,147,483,647
(9,223,372,036,854,775,807
for 64 bit) will produce wrong results.std::string::size()
返回size_t
,它是无符号的,因此无法处理负数。这就是为什么当你将它与-1
相乘时,你会得到这样的答案std::string::size()
returnssize_t
which is unsigned so cannot handle negetive numbers. thats why when you multiply it with-1
you get this kind of answersize()
的结果是basic_string::size_type
类型,它是无符号的。 积分促销规定:“如果 int 不能代表完整范围的值,则该对象将提升为 unsigned int 类型。”因此,
(-1)*a.size()
的类型是无符号的,然后将其打印出来经过std::cout
相应地。要获得“您想要的”,只需将该值转换为有符号整数,但要小心使用足够大的整数类型,无论平台“位数”如何,例如:
The result of
size()
is of typebasic_string::size_type
, which is unsigned. The Integral Promotions dictate that: "If int cannot represent the full range of values, then the object is promoted to type unsigned int."So, the type of
(-1)*a.size()
is unsigned, which than then gets printed bystd::cout
accordingly.To get "what you want", simply cast that value to a signed integer, but be careful the use the integer type that is large enough regardless of platform "bitness", for example:
在
(-1)*a.size()
中,(-1)
的类型为int
和a.size()< /code> 具有无符号类型(可能是
size_t
)。(-1)*a.size()
计算为无符号整数,因为当二进制运算应用于有符号类型和无符号类型时,提升和转换规则有利于无符号类型。In
(-1)*a.size()
,(-1)
has typeint
anda.size()
has an unsigned type (probablysize_t
).(-1)*a.size()
is computed as an unsigned integer, because promotion and conversion rules favor unsigned types when binary operations are applied to a signed type and an unsigned type.size() 返回一个无符号整数。尝试在相乘之前将 size() 的结果显式转换为有符号 int 或 float...应该可以做到。
size() returns an unsigned integer. Try explicitly casting size()'s result to a signed int or float before multiplying... that should do it.