• LeetCode运行报错: reference binding to null pointer of type 'value_type'


    在LeetCode做题的过程中,遇到"reference binding to null pointer of type ‘value_type’" 这个问题,现在对这个问题进行一下分析和总结。

    产生原因:

    1.对于一些stl和一些数据结构掌握不准确。
    2.忽视判断条件。

    错误种类:

    1.测试样例输入为非空数组情况:

    Runtime Error Message:
    reference binding to null pointer of type 'value_type'
    Last executed input:
    [1]
    
    Runtime Error Message:reference binding to null pointer of type 'value_type'
    Last executed input:[[1,1,1],[1,0,1],[1,1,1]]
    

    可能原因:
    a.数组越界,在对vector初始化的时候没有初始化到合适大小,而在接下来的使用中使用了越界的下标。
    例:

    class Solution {
    public:
        int maxProfit(vector<int>& nums) {
            int len = prices.size();
            vector<int> sold(len - 1, 0); // 初始化长度为len - 1
            for (int i = 1; i < len; i++) {
                sold[i] = 1; // 越界
            }
            return sold[len - 1]; // 访问越界
        }
    };
    

    二维数组初始化例子2:

    法一:
    vector<vector<int>>vis(m, vector<int>(n, 0));
    
    法二:
    vector<vector<bool>> visited(rows);// 这里要进行初始化
    for (int i = 0;  i < visited.size(); i++) 
        visited[i].resize(cols); // 这里也要进行初始化
    for(int i=0;i<visited.size();++i){
        for(int j=0;j<visited[0].size();++j){
            visited[i][j] = false;
        }
    }
    

    b.对于vector构建出来的二维数组没有进行空间的申请,比如有些返回类型为vector<vector<>>类型的函数,对于这个返回值vector表示的二维数组要先申请大小,否则使用下标访问就会报这类错误。
    例:

    vector<vector<int>> imageSmoother(vector<vector<int>>& M) {
        vector<vector<int>> res(M.size()); // 这里要进行初始化
        for (int i = 0;  i < res.size(); i++) res[i].resize(M[0].size()); // 这里也要进行初始化
        for (int i = 0; i <  M.size(); i++) {
            for (int j = 0; j < M[0].size(); j++) {
                res[i][j] = 1;
            }
        }
        return res;
    }
    

    2.测试样例输入为空数组情况:

    Runtime Error Message:reference binding to null pointer of type 'value_type'
    Last executed input:[]
    

    可能原因:
    对于数组长度为0的情况没有进行判断,加入判断条件就可以解决。

    总结

    这类错误多数是因为在编程的过程中由于一些判断或者初始化细节没有考虑到,解决起来很简单,但是也容易让人忽视。

    原文链接:https://blog.csdn.net/m0_38088298/article/details/79249044

  • 相关阅读:
    【BZOJ4864】[BeiJing 2017 Wc]神秘物质 Splay
    【BZOJ3438】小M的作物 最小割
    【BZOJ3436】小K的农场 差分约束
    【BZOJ2879】[Noi2012]美食节 动态加边网络流
    【BZOJ1070】[SCOI2007]修车 费用流
    【BZOJ1486】[HNOI2009]最小圈 分数规划
    搜索ABAP程序代码中的字符串
    自定义表的维护
    用户名转换成中文名
    日期计算
  • 原文地址:https://www.cnblogs.com/dindin1995/p/13059079.html
Copyright © 2020-2023  润新知