Nag*_*Psv 3 c++ arrays runtime-error
此代码输入一个整数数组,其中 1 ? [i] ? n (n = 数组的大小),有些元素出现两次,有些元素出现一次。我们必须返回丢失的数字。
输入:[4,3,2,7,8,2,3,1] 输出:[5,6]
它在 Dev C++ 中完全正常,但是当我提交一个名为 leetcode 的网站时,它给了我以下错误
运行时错误消息:
第 924 行:字符 9:运行时错误:引用绑定到类型为“int”(stl_vector.h)的空指针总结:UndefinedBehaviorSanitizer:undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8 /../../../../include/c++/8/bits/stl_vector.h:933:9
vector<int> findDisappearedNumbers(vector<int>& nums)
{
vector<int> temp;
const int len = nums.size();
int j=0;
//sorted the array
sort(nums.begin(), nums.end());
//Added non-repetitive numbers into a temp vector
for(int i=0;i<len;i++)
{
if(nums[i]!=nums[i+1])
{
temp[j++]=nums[i];
}
}
//cleared nums vector for later use
nums.erase(nums.begin(), nums.end());
//added missing numbers in the sequence to both temp and nums vectors
for(int i=0;i<len;i++)
{
if(temp[i]!=i+1)
{
temp.insert(temp.begin()+i, i+1);
nums.insert(nums.end(),i+1);
}
}
return nums;
}
Run Code Online (Sandbox Code Playgroud)
我知道这段代码效率低下,我刚开始使用 C++,但有人能告诉为什么它在网站上不起作用吗?
temp当你这样做时,你的向量是空的:
temp[j++]=nums[i];
Run Code Online (Sandbox Code Playgroud)
因此,您正在访问越界元素。这是未定义的行为,您不能对结果有任何期望。任何事情都可能发生。一旦您的代码包含 UB ,编译器就不再有任何义务。
| 归档时间: |
|
| 查看次数: |
1313 次 |
| 最近记录: |