Search code examples
c++vectoriteratorerase

Erasing an element of a vector that uses const_iterator


I have a vector of Car objects, declared as

vector<Car> vCars

In one of my functions, I need to erase the first element of the vector. Sounds simple enough right? The line that is throwing the error:

vCars.erase( vCars.begin() );

And the error:

no matching function for call to 'std::vector<Car>::erase(std::vector<Car>::const_iterator) const'

I understand erase generally only takes an iterator for its parameter, and not a const_iterator. I've been looking for solutions or workarounds to the error, such as the erase-remove idiom, but from what I'm seeing, that only removes an element by value, when I need to be removing by position - and simply enough, just the element at the first position! (I know this is not good performance wise for a vector, but I am required to use a vector for this)

edit: To clarify the situation, the function the call is contained within is below:

    /// Removes the Car at the front of the garage without returning the instance.
    void Garage::pop() const {
        if ( !empty() ) {
          vCars.erase( vCars.begin() );
        }
    }

edit: And I now see where I went wrong. There were a lot of methods that were const and I just mindlessly made pop() a const method! Once I removed const, the problem was resolved. Thanks for pointing me in the right direction!


Solution

  • The error message:

    no matching function for call to 'std::vector::erase(std::vector::const_iterator) const'

    implies that vCars.begin() yields a const_iterator, which in turn implies that vCars is a constant object or reference. You are not allowed to modify the vector through that reference. If the function needs to modify the vector, it cannot take a constant reference.

    Note that in a member function declared as const the implicit this pointer is of type T const * (i.e. you cannot modify the object inside a const function). If this is your case, you will need to drop the const qualifier from the function.