【发布时间】:2016-04-26 20:42:02
【问题描述】:
following example 将无法使用 g++ 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;
}
编译器会这样说。 (它的可读性不是很好,但它抱怨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,有什么好的解决方法?
【问题讨论】:
-
它还没有实现。
-
这很烦人...问题已编辑;有什么好的解决方法?
-
解决方法是使用非常量迭代器。
-
用
begin代替cbegin? -
@WeaselFox 这对于 const 地图对象是不可能的(至少在没有强制转换的情况下是不可能的)