简体   繁体   English

为什么程序在迭代 c++ 中的 emtpy 向量时抛出运行时错误

[英]Why program throws runtime error while iterating over an emtpy vector in c++

vector <int> o;    //Empty vector
for(int i=0;i<=o.size()-1;i++) cout<<o[i]; 

got runtime error in the above在上面得到运行时错误

vector <int> o;  
for(auto j : o){
 cout<<j<<" ";
            } 

However this code runs fine if iterator is used instead但是,如果使用迭代器,则此代码运行良好

o.size() is required by the C++ standard to return an unsigned type. C++ 标准要求o.size()返回unsigned类型。 When that's zero, subtracting 1 yields std::numeric_limits<decltype(o.size())>::max() which means your loop runs past the bounds of the empty vector.当它为零时,减 1 产生std::numeric_limits<decltype(o.size())>::max()这意味着您的循环运行超过空向量的边界。

for(std::size_t i = 0; i < o.size(); ++i) is the obvious fix. for(std::size_t i = 0; i < o.size(); ++i)是显而易见的解决方法。 The use of <= and -1 seems almost disingenuously contrived to me. <=-1的使用在我看来几乎是不诚实的。

o.size() will return an unsigned value of 0. Subtracting one from it returns a very large positive number, essentially making an infinite loop. o.size()将返回一个无符号值 0。从它减去 1 返回一个非常大的正数,本质上是一个无限循环。 Eventually your out-of-bounds array accesses to o[i] will result in a crash.最终,您对o[i]的越界数组访问将导致崩溃。

You could use你可以用

for(int i = 0; i <= int(o.size() - 1); i++)

Or just use the more typical或者只是使用更典型的

for(int i = 0;i < o.size(); i++)

where you check for "less than", not "less or equal" to a number one less.在那里您检查“小于”,而不是“小于或等于”减去一个数字。

Since sizeof(size_t) is greater or equal than sizeof(int) (although this might be implementation dependent) and size_t is unsigned , the int ( 1 ) is converted to size_t .由于sizeof(size_t)大于或等于sizeof(int) (尽管这可能取决于实现)并且size_tunsigned ,因此int ( 1 ) 被转换为size_t

Therefore, in the expression o.size() - 1 , the 1 is implicitly converted to size_t , and o.size() - 1 (which is equivalent to size_t(0 - 1) ) becomes equal to std::numeric_limits<size_t>::max() .因此,在表达式o.size() - 11被隐式转换为size_t ,并且o.size() - 1 (相当于size_t(0 - 1) )变得等于std::numeric_limits<size_t>::max() Therefore, the for loop is entered and accessing your empty o at index 0 results in undefined behavior.因此,进入for循环并访问索引0处的空o导致未定义的行为。

You should:你应该:

for (size_t idx = 0; idx < o.size(); ++idx) { /* ... */ }

If for some reason you need the index to be of type int , you can:如果出于某种原因您需要索引的类型为int ,您可以:

for (int idx = 0; idx < static_cast<int>(o.size()); ++idx) { /* ... */ }

or in your example (which is less common):或在您的示例中(不太常见):

for (int idx = 0; idx <= static_cast<int>(o.size()) - 1; ++idx) { /* ... */ }

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

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