从size_t减去会导致大正数 [英] subtraction from size_t results in large positive number
本文介绍了从size_t减去会导致大正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚遇到一个讨厌的错误,其中有一个循环
I just run into a nasty bug where I have a loop
for (auto i = 0; i < vec.size() -1; ++i) {
//
}
,因为vec是空 std :: vector
,因此vec.size()-1在我的系统上的值为 2 ^ 64
.
with vec being an emtpy std::vector
, thus vec.size() -1 evaluates to 2^64
on my system.
编写上述循环的正确方法是什么?
What's the correct way of writing the above loop?
推荐答案
size_t
是无符号类型,因此出现了问题,只需这样做:
size_t
is an unsigned type hence the problem, just do that this way:
for (auto i = 0U; i + 1 < vec.size(); ++i)
添加了
0U
以使 i
无符号(以避免警告),但是我最好使用 size_t
代替 auto 代码>在这种情况下
0U
added to make i
unsigned (to avoid warning), but I would better use size_t
istead of auto
in this case
这篇关于从size_t减去会导致大正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文