对于循环退出条件(size_t与int) [英] For Loop Exit Condition (size_t vs. int)

查看:68
本文介绍了对于循环退出条件(size_t与int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在程序中添加以下内容时:

When I put the following in my program:

for (size_t i = VectorOfStructs.size()-1; i > 0; i--)

它可以正常工作,但"i"永远不会等于0.因此,我无法访问第一个元素(VectorOfStructs [0]).

It works correctly but does "i" will never equal 0. So, I cannot access the first element (VectorOfStructs[0]).

如果我将其更改为:

for (size_t i = VectorOfStructs.size()-1; i > -1; i--)

程序甚至没有进入for循环!但是,如果我将其更改为以下内容:

The program doesn't even enter the for loop! But, if I change it to the following:

for (int i = VectorOfStructs.size()-1; i > -1; i--)

它完全按照我想要的方式工作(遍历所有元素).

It works exactly as I want it to (Iterates through all the elements).

所以,我的问题是:

(A)为什么第二代码段无法执行?

(B)为什么第三个代码片段会相应执行,而第二个代码片段却无法执行?

任何见识将不胜感激!

推荐答案

第二个示例使用 size_t 作为 i 的类型,该类型是 unsigned 类型,因此它永远不能有负值;这也意味着它不能与 -1

The second example uses size_t as type for i, which is an unsigned type, thus it can never have negative values; this also means that it cannot be properly compared with -1

但是(int)-1 的位表示为 0xFFFFFFFF ,它表示一个相当大的数字( 2 ^ 32-1 )表示 size_t . i> 0xFFFFFFFF 永远不能为真,因为 0xFFFFFFF size_t 可以容纳的最大值.

But (int)-1 is bit-represented as 0xFFFFFFFF, which represents a rather large number (2^32-1) for size_t. i>0xFFFFFFFF can never be true, since 0xFFFFFFF is the largest value a size_t can ever hold.

第三个示例使用 signed int (允许使用负数,因此测试成功).

The 3rd example uses signed int (which allows for negative numbers and therefore the test succeeds).

这应该工作:

for (size_t i = VectorOfStructs.size(); i-- > 0;) {
  use(VectorOfStructs[i]);
}

这篇关于对于循环退出条件(size_t与int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆