简体   繁体   English

为什么for循环没有停止?

[英]Why for loop is not stopping?

I have a for loop in my program that is not stopping:我的程序中有一个没有停止的for循环:

vector<int> v;
int k = 1;
v.push_back(1);

for(int i=v.size()-1; i>=(v.size()-k); i--){
    cout << i << " " << v.size() - k << endl;
}

When I execute the above program, it keeps running inside the for loop.当我执行上述程序时,它一直在for循环内运行。 The output of the for loop is as below: for循环的output如下:

0 0
-1 0
-2 0
-3 0
-4 0
.
.
.

As per the output, value of i is decreasing and value of v.size()-k is 0. So, i >= v.size()-k is false, which should stop the for loop to execute after the first round, But the for loop doesn't stop executing.根据 output, i的值正在减小, v.size()-k的值为 0。因此, i >= v.size()-k为假,这应该在第一轮之后停止for循环执行, 但for循环并没有停止执行。

Can someone help me understand this issue?有人可以帮我理解这个问题吗?

You are checking if i is greater than or equal to zero.您正在检查i是否大于或等于零。 But since size() returns an unsigned, you are comparing i to an unsigned zero.但是由于size()返回一个无符号数,因此您将i与一个无符号数零进行比较。 To do the comparison, i is converted to the same unsigned type that size() returns.为了进行比较,将i转换为与size()返回的相同的无符号类型。 Well, every unsigned integral value is greater than or equal to zero.好吧,每个无符号整数值都大于或等于零。 So whatever value i has, the comparison is true.所以无论i有什么价值,比较都是真的。

The size() function has to return a type large enough to hold the maximum number of entries that might be in a vector. size() function 必须返回一个足够大的类型以容纳向量中可能存在的最大条目数。 That can be larger than the largest value an int can hold.这可能大于int可以容纳的最大值。 On typical modern platforms, int might be a 32-bit signed type while size() returns a 64-bit unsigned.在典型的现代平台上, int可能是 32 位有符号类型,而size()返回 64 位无符号类型。

Here's the warning from my compiler:这是我的编译器发出的警告:

a.cpp: In function ‘int main()’:
a.cpp:10:28: warning: comparison of integer expressions of different signedness:
             ‘int’ and ‘std::vector<int>::size_type’
             {aka ‘long unsigned int’} [-Wsign-compare]
   10 |     for(int i=v.size()-1; i>=(v.size()-k); i--){
      |                           ~^~~~~~~~~~~~~~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM