LeetCode中問題1.reference binding to null pointer of type 'const value_type'

問題1:reference binding to null pointer of type 'const 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]; // 訪問越界
    }
};

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的情況沒有進行判斷,加入判斷條件就可以解決。

總結

這類錯誤多數是因爲在編程的過程中由於一些判斷或者初始化細節沒有考慮到,解決起來很簡單,但是也容易讓人忽視。

--------------------- 本文來自 seven_- 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/m0_38088298/article/details/79249044?utm_source=copy

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章