引用绑定到类型为'value_type'的空指针 [英] reference binding to null pointer of type 'value_type'

查看:107
本文介绍了引用绑定到类型为'value_type'的空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是leetcode26.给定排序数组,就地删除重复项,以使每个元素仅出现一次并返回新的长度.给出一个示例 nums = [1,1,2] ,该函数应返回 [1,2] .

This is leetcode 26. Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. An example is given nums = [1,1,2], the function should return [1,2].

下面是我的代码.我删除所有其他重复项,只保留其中一个.但是,提交时,总是出现 reference绑定到'value_type'类型的空指针的错误.如果有人可以帮助我,我将不胜感激!

Below is my code. I delete all the other duplicates, just leave one of them. However I always got an error of reference binding to null pointer of type 'value_type' when submitting. I would appreciate if anyone can help me with this!

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        while(i < nums.size() - 1) {
            if (nums[i] == nums[i + 1]) {
                nums.erase(nums.begin() + i);
            } 
            else i++;
        }
        return nums.size();
    }
};

推荐答案

vector< T> :: size()返回类型为 size_t 的值无符号类型.假设传入的向量为空,因此向量的长度为0. nums.size()-1 将导致整数下溢,您实际上将把 0 与一个非常大的正数.这将评估为true,从而导致循环运行,并且 i 越过数组范围.

vector<T>::size() returns a value of type size_t, which is an unsigned type. Let's say the vector passed in is empty and therefore the vector's length is 0. nums.size() - 1 will cause integer underflow and you will actually be comparing 0 with a very large positive number. This will evaluate to true causing the loop to run and i going pass the array bounds.

要解决此问题,您可以抢先将 nums.size()强制转换为 int 或将大小存储在整数变量中并与之进行比较.

To fix this you can cast nums.size() to int preemptively or store the size in an integer variable and compare with that.

这篇关于引用绑定到类型为'value_type'的空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆