skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. your code tries to remove successive duplicates only, hence the function name is not clear.

    You use indexes in the wrong way. The indexes start at 0 and end at nums.size() -1.

    check this https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom

    and if u would define k before the while loop its a for loop without any doubt

    Example of a working code.

    void removeSuccessiveDuplicates(std::vector<int>& nums) {
        size_t end = nums.size();
        for (size_t k = 0; k < end - 1; ++k) {
            if (nums[k] == nums[k + 1]) {
                for (size_t i=k+1;i<end-1;++i){std::swap(nums[i], nums[i+ 1]);}
                --end;
                --k; // Check the current index again in the next iteration
            }
        }
        nums.resize(end);
    }
    

    I could have used std::remove_if with std::erase or used rotate in the current example but I just wanted to emphasize how ur code could be corrected

    play with it here https://godbolt.org/z/j8f957T58

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search