suraj
suraj

Reputation: 69

reference binding to null pointer of type 'int' (stl_iterator.h)

can someone help me to solve this error

Line 786: Char 17: runtime error: reference binding to null pointer of type 'int' (stl_iterator.h)

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int>result;
        sort(nums.begin(),nums.end());
        int p=1;
        int minel=*min_element(nums.begin(),nums.end());
        int maxa=*max_element(nums.begin(),nums.end());
        for(int64_t i=minel;i<=maxa;i++)
        {
            int c=count(nums.begin(),nums.end(),i);
            if(c==0)
            {
                result.push_back(i);
            }
        }
        return result;
    }
};

Upvotes: 0

Views: 1852

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122575

Things can fail and when you use something that can fail you should check if it did or not. In particular std::max_element returns...

Iterator to the greatest element in the range [first, last). If several elements in the range are equivalent to the greatest element, returns the iterator to the first such element. Returns last if the range is empty.

You should change this

int minel=*min_element(nums.begin(),nums.end());

to

auto it = min_element(nums.begin(),nums.end());
if (it != nums.end()) {
    auto minel = *it;
}  else {
    // do not use it
}

Alternatively check if nums is empty once at the beginning of the function. The code seems to be for a online contest. Check the requirements, if an empty input is valid input you need to handle it. If empty vector is not a requirement you have to handle you might have a bug in code that you did not show.

Upvotes: 1

Related Questions