I am just practicing c++ on leetcode: https://leetcode.com/problems/asteroid-collision/description/
and I have problem with vector overflow.
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 1) >= this->size() (which is 1)
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids)
{
auto left = 0;
auto right = asteroids.size() - 1;
while (left <= right) {
if (left == right) {
return asteroids;
}
if ((asteroids.at(left) > 0 && asteroids.at(right) < 0) || (asteroids.at(left) < 0 && asteroids.at(right) > 0)) {
if (abs(asteroids.at(left)) == abs(asteroids.at(right))) {
asteroids.erase(asteroids.begin() + right);
// until this everything seems fine
asteroids.erase(asteroids.begin() + left);
left++;
right--;
}
if (abs(asteroids.at(left)) > abs(asteroids.at(right))) {
asteroids.erase(asteroids.begin() + right);
right--;
}
if (abs(asteroids.at(left)) < abs(asteroids.at(right))) {
asteroids.erase(asteroids.begin() + left);
left++;
}
}
cout << asteroids.size();
}
return asteroids;
}
};
I know that erase shrinks the size of my vector, but I can't see how the out_of_range occures
EDIT: this is my first version of the code, I know that I can write it more simpler(like less if statements or abs() ect. ), but fisrt I want to know the reason of codes failure.