且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对于循环退出条件(size_t与int)

更新时间:2023-11-14 21:58:28

第二个示例使用 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]);
}