Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 对空指针的引用绑定_C++_Arrays - Fatal编程技术网

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());