Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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

like image 305
Shivam Garg Avatar asked Nov 28 '22 21:11

Shivam Garg


1 Answers

o.size() is required by the C++ standard to return an unsigned type. 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.

for(std::size_t i = 0; i < o.size(); ++i) is the obvious fix. The use of <= and -1 seems almost disingenuously contrived to me.

like image 87
Bathsheba Avatar answered Dec 05 '22 19:12

Bathsheba