std::vector:<int>:擦除在编译中失败

std::vector<int>::erase failed in compilation

本文关键字:编译 失败 擦除 int vector lt std gt      更新时间:2023-10-16

我有一段代码,我首先定义了

std::vector<int> half_gid_m;

通过push_back函数计算向量half_gid_m的元素。然后对向量执行sort和unique函数:

sort(half_gid_m.begin(),half_gid_m.end());
std::vector<int>::iterator itv( std::unique(half_gid_m.begin(),half_gid_m.end()) );

最后,我擦除向量中重复条目为

的部分
half_gid_m.erase(itv,half_gid_m.end());

看起来一切正常,但是编译给了我这个奇怪的错误

error: no matching function for call to 'std::vector<int, std::allocator<int>    >::erase(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >&) const'
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc:110: note: candidates are: typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = int, _Alloc = std::allocator<int>]
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc:122: note:                 typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = int, _Alloc = std::allocator<int>]
//home/gales/ingv/p-gales/simulations/little_mesh/lib/p-gales/include/gales-0.1/gales/map/map_rule.hpp:166: error: no matching function for call to 'std::vector<int, std::allocator<int> >::erase(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >&) const'
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc:110: note: candidates are: typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = int, _Alloc = std::allocator<int>]
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc:122: note:                 typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = int, _Alloc = std::allocator<int>]

我真的不明白问题出在哪里,因为vector、push_back、sort和unique操作都是用正确的方式写的。

有人能帮我吗?

意思是说error: no matching function for call to 'std::vector::erase(...) const。也就是说,你在一个常量向量上调用erase,而erase是一个非常量成员函数。