我正在尝试使用擦除功能从向量中删除值为0的所有整数。
void eliminateZeroes(std::vector<int> &answers){
auto i = answers.cbegin();
while(i != answers.cend()){
if(*i == 0){
i = answers.erase(i);
}else{
i++;
}
}
我希望函数从向量中删除所有值为0的项。
错误消息:
/home/ec2-user/environment/DP378-Havel_Hakimi_-_Easy/main.cpp: In function ‘void eliminateZeroes(std::vector<int>&)’:
/home/ec2-user/environment/DP378-Havel_Hakimi_-_Easy/main.cpp:32:36: error: no matching function for call to ‘std::vector<int>::erase(__gnu_cxx::__normal_iterator<const int*, std::vector<int> >&)’
i = answers.erase(i);
^
/home/ec2-user/environment/DP378-Havel_Hakimi_-_Easy/main.cpp:32:36: note: candidates are:
In file included from /usr/include/c++/4.8.5/vector:69:0,
from /home/ec2-user/environment/DP378-Havel_Hakimi_-_Easy/main.cpp:1:
/usr/include/c++/4.8.5/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.5/bits/vector.tcc:134:5: note: no known conversion for argument 1 from ‘__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.5/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.5/bits/vector.tcc:146:5: note: candidate expects 2 arguments, 1 provided
答案 0 :(得分:3)
似乎您使用的是不完全支持C ++ 11标准的旧编译器。
问题在于函数auto i = answers.cbegin();
erase
不能转换为C ++ 11标准之前的成员函数iterator erase(const_iterator position);
的旧声明中使用的非常数迭代器。
在当前的C ++标准中,该函数的声明类似于
auto i = answers.cbegin();
,您的代码应编译。
所以不是
auto i = answers.begin();
您需要使用
#include <vector>
#include <algorithm>
std::vector<int> & eliminateZeroes( std::vector<int> &answers )
{
answers.erase( std::remove( answers.begin(), answers.end(), 0 ), answers.end() );
return answers;
}
但是无论如何,最好通过以下方式定义函数
begin
如果您的编译器支持标头end
中声明的通用函数<iterator>
,#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> & eliminateZeroes( std::vector<int> &answers )
{
answers.erase( std::remove( std::begin( answers ), std::end( answers ), 0 ), std::end( answers ) );
return answers;
}
等,则该函数也可以像
except (TypeError, AttributeError):
return na_value