no matching function to call `erase` (std::vector)

Viewed 208

I am trying to erase an element from std::vector<int>. Here's the code :

//vector_remove.cpp

#include <vector>
    
int main()
{
    std::vector<int> ints { 1, 2, 3 };
    
    for( auto it = ints.cbegin(); it != ints.cend(); )
    {
        if( (*it) == 1 )
        {
            it = ints.erase( it );
        }
        else
        {
            ++it;
        }
    }
    
    return 0;
}

Compilation is as follows:

g++ -std=c++11 vector_remove.cpp -o main

But I get the following error:

vector_remove.cpp: In function ‘int main()’:
vector_remove.cpp:11:33: error: no matching function for call to ‘std::vector<int>::erase(__gnu_cxx::__normal_iterator<const int*, std::vector<int> >&)’
             it = ints.erase( it );
                                 ^
vector_remove.cpp:11:33: note: candidates are:
In file included from /usr/include/c++/4.8.2/vector:69:0,
                 from vector_remove.cpp:1:
/usr/include/c++/4.8.2/bits/vector.tcc:134:5: note: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(std::vector<_Tp, _Alloc>::iterator) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = int*]
     vector<_Tp, _Alloc>::
     ^
/usr/include/c++/4.8.2/bits/vector.tcc:134:5: note:   no known conversion for argument 1 from ‘__gnu_cxx::__normal_iterator<const int*, std::vector<int> >’ to ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’
/usr/include/c++/4.8.2/bits/vector.tcc:146:5: note: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(std::vector<_Tp, _Alloc>::iterator, std::vector<_Tp, _Alloc>::iterator) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = int*]
     vector<_Tp, _Alloc>::
     ^
/usr/include/c++/4.8.2/bits/vector.tcc:146:5: note:   candidate expects 2 arguments, 1 provided

I understand the error : the erase function expects iterator not const_iterator. But I don't understand why. I am using the C++11 standard and from this I see that it should be OK to use const_iterator here.


g++ --version output:

g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39)
0 Answers
Related