[英]Runtime error: reference binding to null pointer of type 'int' (stl_vector.h) c++
I know that this error refers to undefined behavior (I think), but I've reread my code 20 times and I don't see what the UB is!?我知道这个错误是指未定义的行为(我认为),但我已经重读了我的代码 20 次,但我没有看到 UB 是什么!?
I'm doing Leetcode 238. Product of Array Except Self and here's my code (btw I don't know if this solution is right):我正在做 Leetcode 238. 除了 Self 的数组的乘积,这是我的代码(顺便说一句,我不知道这个解决方案是否正确):
class Solution { public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> result;
map<int, int> map;
for(int i = 0; i < nums.size(); i++){
map[i] = nums[i];
}
for(int i = 0; i < nums.size(); i++){
for(auto& it : map){
if(it.first != i){
result[i] = nums[i] * result[i];
}
}
}
return result;
} };
You can replace vector<int> result;
您可以替换
vector<int> result;
with vector<int> result(nums.size());
与
vector<int> result(nums.size());
This will initialize all of the values of result
to 0. It won't solve the problem, but it will get rid of the runtime error you're getting.这会将
result
的所有值初始化为 0。它不会解决问题,但会消除您遇到的运行时错误。
Follow this:按照这个:
result[i] = nums[i] * result[i];
The element value result
is not initialized before.元素值
result
之前没有初始化。
Refer this:参考这个:
if (i == 0)
result.push_back(nums[i]);
else
result.push_back(nums[i] * result.at(i-1));
if necessary如有必要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.