在c++运行时错误:在Leetcode中添加了无符号偏移量



在Leetcode中解决最长连续序列时,我得到了这个错误,但我没有得到为什么我得到它。

运行时错误:添加无符号偏移到0x603000000070溢出到0x60300000006c (stl_vector.h)UndefinedBehaviorSanitizer:未定义的行为

int longestConsecutive(vector<int>& nums) {
sort(nums.begin(),nums.end());

int curr = 1;
int longest = 1;
for(int i =0;i<nums.size();i++){
if(nums[i] != nums[i - 1] )//The numbers can be same
{
if(nums[i] == nums[i - 1]  +1){
curr += 1;
}
else{   ///Update only when the distorted sequence is found
longest = max(longest,curr);
curr = 1;    
}
}
}
return max(curr,longest);
}

问题是,在第一次for循环迭代,你得到i=0,并检查如果nums[i] != nums[i-1],所以它成为nums[0] != nums[-1],这是UB,因为nums[-1]是未初始化的,不属于向量数据实际上。

问题是,在for中,i的第一个值是0,然后到nums[i-1],它抛出异常。

最新更新