[英]For loop in c++ is not running while using this way: for(int i=-1;i<vector.size();i++) cout << i << endl;
I have a particular use case where I have to initialize i value in for loop to -1 and write the exiting condition based on vector size.我有一个特殊的用例,我必须将 for 循环中的 i 值初始化为 -1 并根据向量大小编写退出条件。 But the problem is the loop is not getting executed at all.
但问题是循环根本没有被执行。 This is the code.
这是代码。
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };
for(int i=-1;i<vec.size();i++) cout << i << " ";
return 0;
}
But I am able to do like this.但我可以这样做。
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };
int size = vec.size();
for(int i=-1;i<size;i++) cout << i << " ";
return 0;
}
Can anyone explain this weird behavior or am I doing something wrong there?谁能解释这种奇怪的行为,还是我在那里做错了什么?
i<size()
in the first snippet compares a signed int i;
第一个片段中的
i<size()
比较有符号的int i;
to an unsigned size_t size;
为无符号
size_t size;
( size_t
is the typical typedef for vector::size_type
) (
size_t
是vector::size_type
的典型 typedef)
When the compiler sees that comparison, it converts the int
to an unsigned value.当编译器看到该比较时,它会将
int
转换为无符号值。 Typically something like 2^64 - 1
, for your first value of -1
.通常类似于
2^64 - 1
,用于您的第一个值-1
。 This value is much bigger than 5, so the loop doesn't run.该值远大于 5,因此循环不会运行。
Take-away: Don't compare signed and unsigned value with less-than or greater-than.要点:不要将有符号和无符号值与小于或大于进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.