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. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With