[英]How to initialize a vector with -2147483648 in C++
I found the problem when initializing a vector with value -2147483648 我初始化带有值-2147483648的向量时发现了问题
vector<int> vec1({-2147483648}); // invalid, error C2440
vector<int> vec2({0, -2147483648}); // invalid, error C2398
int a = -2147483648;
vector<int> vec3({t}); // valid
vector<int> vec4({0, t}); // valid
vector<int> vec5(1, -2147483648); // valid
The problem appears when I use VS2013. 当我使用VS2013时出现问题。 Does anyone know why?
有人知道为什么吗?
-2147483648
is a unary negation operator applied to an integral literal 2147483648
. -2147483648
是应用于整数文字2147483648
的一元求反运算符。 The latter does not fit into an int
(assuming it's 32-bit), which means that -2147483648
is actually an expression of unsigned
type. 后者不适合
int
(假设它是32位),这意味着-2147483648
实际上是unsigned
类型的表达式。
Now, unsigned
can be implicitly converted to int
(when the value is unrepresentable, the result is technically implementation-defined, but usually unsurprising). 现在,可以将
unsigned
隐式转换为int
(当值无法表示时,结果从技术上讲是实现定义的,但通常并不令人惊讶)。 However, this is a narrowing conversion, which is prohibited when used with brace initialization. 但是,这是一个缩小的转换,与大括号初始化一起使用时是禁止的。
Instead of attempting to write the value as a literal, just use INT_MIN
from the <limits.h>
header, or std::numeric_limits<int>::min()
from the <limits>
header, assuming that your intention is to express the minimum value of an int
. 无需尝试将值写为文字,只需使用
<limits.h>
标头中的INT_MIN
或<limits>
标头中的std::numeric_limits<int>::min()
, INT_MIN
是您要表达一个int
的最小值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.