c++ - 为什么程序在 C++ 中迭代空 vector 时会抛出运行时错误

标签 c++ vector

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

在上面得到运行时错误
vector <int> o;  
for(auto j : o){
 cout<<j<<" ";
            } 

但是,如果 ,此代码运行良好迭代器 改为使用

最佳答案

o.size() C++ 标准要求返回 unsigned类型。当它为零时,减去 1 产生 std::numeric_limits<decltype(o.size())>::max()这意味着您的循环运行超过了空 vector 的边界。
for(std::size_t i = 0; i < o.size(); ++i)是显而易见的解决办法。 <=的使用和 -1在我看来几乎是不诚实的做作。

关于c++ - 为什么程序在 C++ 中迭代空 vector 时会抛出运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60209328/

相关文章:

c++ - DwmExtendFrameIntoClientArea 不起作用

c++ - std::for_each 在具有两个参数的成员函数上的用法

c++ - 结构 vector C++

c++ - 为什么我随机生成的数字输入全零?

c++ - 抑制谷歌测试断言的输出

c++ - 如何为 map 提供默认值?

c++ - Vector Add的STL算法

c++ - 找到连续的最小值并在队列 vector 中进行比较

c++ - 在递归数据结构中 move unique_ptr<T> 数组

C++ 在类中声明数组并在类中声明二维数组