Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I keep getting Microsoft C++ exception: std::out_of_range at memory location 0x000000B70C8FF360. when using vector?

Visual studio shows 0 issues found but when program starts, a tab pop up with vector library and points on line 2151 and says "Unhandled exception at 0x00007FF90121CF19 in Project2.exe: Microsoft C++ exception: std::out_of_range at memory location"

I wrote a code that checks vector position (k) with next vector position (k + 1) and if it has the same number it removes position (k)
It should stop checking and removing duplicates after it reaches size of vector but I keep getting the exception error. I tap continue and it works fine but still after every "continue" it shows an exception error. How to stop getting that?

void removeDuplicates(vector<int>& nums) {
    int k = 0;
    while (k != nums.size() + 1) {
        vector<int>::iterator iter = nums.begin() + k;
        if (nums.at(k) == nums.at(k + 1)) {
            nums.erase(iter);
        }
        ++k;
    }
}

I tried to tap continue and it works fine but still after every "continue" it shows an exception error.
In code I tried to remove arithmetical operators next to "nums.begin()" and inside brackets of "nums.at()" but it didnt help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Surely you want to check k < nums.size() to stay within bounds. You could check k != nums.size() but then your loop could do something clever like increment k by a bigger number than 1 and skip right over nums.size().

But then you index with k + 1, so you probably want k < nums.size() - 1 as your condition.

I would suggest that unless you’re absolutely required to modify the original, you return a new vector containing these values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading