首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >缺少const_iterator重载的std::g++::g++::g++ 4.8

缺少const_iterator重载的std::g++::g++::g++ 4.8
EN

Stack Overflow用户
提问于 2013-10-24 07:09:02
回答 2查看 3.5K关注 0票数 11

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

代码语言:javascript
复制
#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_iteratorvector<int>::iterator之间没有已知的转换。)

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-24 07:13:44

这是gcc的一个已知bug:bug.cgi?id=57158

擦除需要一个迭代器,而不是当前gcc的const_iterator。

票数 14
EN

Stack Overflow用户

发布于 2015-07-11 16:53:58

您可以通过指针算法获得一个非const迭代器,下面是一个帮助函数:

代码语言:javascript
复制
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());
  }

使用方式如下:

代码语言:javascript
复制
std::vector<T> v(1);
auto citer = v.cbegin();
v.erase( const_iterator_cast(v, citer) );
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19559235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档