"no matching function for call" 尝试对矢量使用擦除功能时

"no matching function for call" when trying to use the erase function on a vector

我正在尝试使用擦除函数从我的向量中删除任何值为 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

看来您使用的是不完全支持 C++ 11 标准的旧编译器。

问题是函数cbegin

产生的常量迭代器
auto i = answers.cbegin();

无法转换为在 C++ 11 标准之前的成员函数 erase 的旧声明中使用的非常量迭代器。

在当前的 C++ 标准中,函数声明为

iterator erase(const_iterator position);

你的代码应该可以编译。

所以

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;
}

如果你的编译器支持在头文件中声明的通用函数 beginend 等等 <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;
}