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
Surely you want to check
k < nums.size()
to stay within bounds. You could checkk != nums.size()
but then your loop could do something clever like incrementk
by a bigger number than1
and skip right overnums.size()
.But then you index with
k + 1
, so you probably wantk < 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.
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.
I could have used
std::remove_if
withstd::erase
or used rotate in the current example but I just wanted to emphasize how ur code could be correctedplay with it here https://godbolt.org/z/j8f957T58