-2

我有一个用户定义数据类型的向量city。我试图通过它的 ID 从这个向量中删除一个元素;最终,所有城市都会从这个列表中while(!cityList.empty())循环删除。我打算使用erase-remove 成语来完成此操作。

但是,当我调用remove(). 将city对象作为第三个参数传入会remove()导致此错误,就像传入city. 此错误不会发生erase(),但会发生remove(),并且find()如果我尝试使用它。这是有问题的代码:

vector<city> cityList;
cityList.push_back(city(1));
cityList.push_back(city(2));
cityList.push_back(city(3));

city cityToRemove = cityList[0];
int idOfCityToRemove = cityList[0].getID();

remove(cityList.begin(), cityList.end(), cityToRemove);
//remove(cityList.begin(), cityList.end(), idOfCityToRemove);

这是我的问题的更新的简单,最小的演示

错误消息包括“模板参数推导/替换失败”“'city' 不是从 'const _gnu_cxx::__normal_iterator<_IteratorL, _Container>' 派生的”消息,我无法在网上找到任何与我的上述错误的问题。

编辑:我已经修改了我的代码,现在我有了:

int main(int argc, char** argv) {

vector<city> cityList;
cityList.push_back(city(1));
cityList.push_back(city(2));
cityList.push_back(city(3));

city cityToRemove = cityList[0];
int idOfCityToRemove = cityList[0].getID();
int i;

for (i = 0; i < cityList.size(); i++) {
    cityList.erase(remove_if(cityList.begin(), cityList.end(),  cityList[i] == cityToRemove), cityList.end());
}
//remove(cityList.begin(), cityList.end(), cityToRemove);
//remove(cityList.begin(), cityList.end(), idOfCityToRemove);

return 0;
}

bool operator ==(const city &a, const city &b)
{
    return (a.id == b.id);
}

我在尝试编译时收到的错误是:

In file included from /usr/include/c++/5/bits/stl_algobase.h:71:0,
             from /usr/include/c++/5/bits/char_traits.h:39,
             from /usr/include/c++/5/ios:40,
             from /usr/include/c++/5/ostream:38,
             from /usr/include/c++/5/iostream:39,
             from main.cpp:2:
/usr/include/c++/5/bits/predefined_ops.h: In instantiation of ‘bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = __gnu_cxx::__normal_iterator<city*, std::vector<city> >; _Predicate = bool]’:
/usr/include/c++/5/bits/stl_algo.h:866:20:   required from _ForwardIterator std::__remove_if(_ForwardIterator, _ForwardIterator, _Predicate) [with _ForwardIterator = __gnu_cxx::__normal_iterator<city*, std::vector<city> >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]’
/usr/include/c++/5/bits/stl_algo.h:936:30:   required from ‘_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = __gnu_cxx::__normal_iterator<city*, std::vector<city> >; _Predicate = bool]’
main.cpp:30:90:   required from here
/usr/include/c++/5/bits/predefined_ops.h:234:30: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
                          ^

这更接近,但我不确定需要什么。然而,这条线main.cpp:30:90指向cityList[i] == cityToRemove我的函数的一部分cityList.erase(),所以我知道问题出在我的比较表达式中。

我的演示也更新了。

4

1 回答 1

0

您需要定义一个operator ==

class city {
    public:
        city(int idin);
        int getID();

    private:
        int id;

    friend bool operator==(const city &a, const city &b);
};

.

bool operator ==(const city &a, const city &b)
{
    return a.id == b.id;
}

并且也erase这里的例子一样调用。

于 2016-09-23T18:44:36.910 回答