Search code examples
c++exceptionmemoryvector

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.


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. You may wish to test if the container is empty, and if so, immediately return.

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