C++ 对空指针的引用绑定
这就是问题的根源C++ 对空指针的引用绑定,c++,arrays,C++,Arrays,这就是问题的根源 class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { vector<int> cons; int count=0; int len=nums.size(); if(nums.empty()) { return
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
vector<int> cons;
int count=0;
int len=nums.size();
if(nums.empty())
{
return 0;
}
else
{
int i=0;
while(i<len)
{
if(nums[i]==1)
{
count++;
}
else
{
cons.push_back(count);
count=0;
}
i++;
}
int val=*max_element(cons.begin(),cons.end());
return val;
}
}
};
添加此条件以检查cons
是否为空
int val=*max_element(cons.begin(),cons.end());
欢迎来到堆栈溢出。请花点时间浏览并参考中的材料,了解您可以在此处询问什么以及如何提问。发布一篇文章特别重要。根据您展示的代码,我注意到的是,您使用的是
max\u元素的结果
,但没有确保它不等于cons.end()
。如果nums
中的所有值都等于1
,则向量cons
可以为空,如果使用某种迭代器检查调试选项编译程序,则可能会导致此类运行时错误。
int val;
if(cons.size()!=0)
val=*max_element(cons.begin(),cons.end());