LeetCode 198打家劫舍C++代码提交出现Runtime error求助
Hey there! That runtime error—reference binding to the null pointer of type 'value_type'—usually crops up when you’re trying to access an element from an empty container (like an empty vector<int>) or when you’re stepping out of bounds with array/vector indices. Let’s walk through the most likely issues with your House Robber code and how to fix them.
Common Causes & Fixes
1. Missing Empty Input Handling
LeetCode’s test cases always include edge cases like an empty input array (nums.size() == 0). If your code tries to access nums[0] or initialize a DP array without checking for this first, you’ll hit that error immediately.
Bad Example:
int n = nums.size(); vector<int> dp(n); dp[0] = nums[0]; // Fails if nums is empty!
Fix: Add an early return for empty inputs:
if (nums.empty()) return 0;
2. Out-of-Bounds Index Access in DP Logic
When setting up your dynamic programming array, it’s easy to slip up and access indices that don’t exist. For example, if your input has only one element, trying to access dp[1] (which doesn’t exist) will trigger the error.
Fix: Handle single-element inputs separately before proceeding with the full DP loop:
int n = nums.size(); if (n == 1) return nums[0];
3. Returning from an Empty DP Array
If you end up trying to return dp.back() when the DP array is empty (because the input was empty), that’ll also throw the null pointer reference error. The early empty check we mentioned earlier prevents this.
Corrected Example Code
Here’s a version of the House Robber solution that avoids all these pitfalls:
class Solution { public: int rob(vector<int>& nums) { // Handle empty input case first if (nums.empty()) return 0; int n = nums.size(); // Handle single-element case separately if (n == 1) return nums[0]; vector<int> dp(n); dp[0] = nums[0]; dp[1] = max(nums[0], nums[1]); // Iterate only within valid bounds for (int i = 2; i < n; ++i) { dp[i] = max(dp[i-1], dp[i-2] + nums[i]); } return dp.back(); } };
Quick Checklist for Your Code
- Did you add a check for
nums.empty()? - Are you handling the single-element input case?
- Do all your index accesses (for
numsanddp) stay within0 <= index < size? - Are you trying to access elements from a container that might be empty?
If you still run into issues, feel free to share your exact code snippet—I can help dig deeper!
内容的提问来源于stack exchange,提问作者jingyao shi

