缺少使用g ++ 4.8的std :: vector :: erase()的const_iterator重载

Geo*_*ard 11 c++ stl g++ c++11

下面的例子将不会编译使用克++ 4.8.2:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v {1, 2, 3};

    v.erase(v.cbegin()); // Compiler complains

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器说如下.(它不是很易读,但它抱怨说vector<int>::const_iterator和之间没有已知的转换vector<int>::iterator.)

prog.cpp: In function ‘int main()’:
prog.cpp:8:20: error: no matching function for call to ‘std::vector<int>::erase(std::vector<int>::const_iterator)’
  v.erase(v.cbegin());
                    ^
prog.cpp:8:20: note: candidates are:
In file included from /usr/include/c++/4.8/vector:69:0,
                 from prog.cpp:2:
/usr/include/c++/4.8/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/bits/vector.tcc:134:5: note:   no known conversion for argument 1 from ‘std::vector<int>::const_iterator {aka __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/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/bits/vector.tcc:146:5: note:   candidate expects 2 arguments, 1 provided
Run Code Online (Sandbox Code Playgroud)

为什么? C++ 11标准明确规定,在§23.3.6.5中,该vector::erase函数采用aconst_iterator.(释义在这里这里.)

什么是一个好的解决方法,假设我必须使用const_iterator

mir*_*irk 14

这是gcc中的已知错误:http://gcc.gnu.org/bugzilla/show_bug.cgi? id = 57158

erase需要一个迭代器而不是一个带有当前gcc的const_iterator.

  • @thirtythreeforty"目标里程碑:4.9.0"已解决并不意味着"固定在每个版本中". (2认同)

Jon*_*ely 8

你可以通过指针算法得到一个非const迭代器,这是一个辅助函数来做到这一点:

template<typename T>
  typename std::vector<T>::iterator
  const_iterator_cast(std::vector<T>& v, typename std::vector<T>::const_iterator iter)
  {
    return v.begin() + (iter - v.cbegin());
  }
Run Code Online (Sandbox Code Playgroud)

像这样使用:

std::vector<T> v(1);
auto citer = v.cbegin();
v.erase( const_iterator_cast(v, citer) );
Run Code Online (Sandbox Code Playgroud)