Looping through vector std::out_of_range'

66 views Asked by At

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.

1

There are 1 answers

0
Jesper Juhl On

You loop for the original size of the vector, but inside the loop you reduce the size of the vector, so you end up accessing out of bounds when accessing beyond the new reduced size.

If the vector initially holds 10 elements you'll loop 10 times and access elements 0-9. And if you erase 1 element, then the only valid indices will be 0-8, so once you hit index 9 you are out-of-bounds.