使用g ++ 4.8.2无法编译following example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v {1, 2, 3};
v.erase(v.cbegin()); // Compiler complains
return 0;
}
编译器说明如下。 (它不是很易读,但它抱怨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
为什么? C ++ 11标准在§23.3.6.5中明确指出vector::erase
函数需要const_iterator
。 (释义是here和here。)
假设我必须使用const_iterator
?
答案 0 :(得分:14)
这是gcc中的已知错误:http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57158
erase需要一个迭代器而不是一个带有当前gcc的const_iterator。
答案 1 :(得分: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());
}
像这样使用:
std::vector<T> v(1);
auto citer = v.cbegin();
v.erase( const_iterator_cast(v, citer) );