我有下面的代码,我正在尝试编写一个通用函数,它需要 2 个迭代器和一个对象,并检查任何出现并返回出现的次数。
在我的简单课下面
class person{
string name;
int age;
public:
person(string n, int a): name(n), age(a) {}
bool operator==(person &p);
};
bool person::operator==(person &p){
return (name == p.name && age == p.age);
}
下面是通用函数
template<typename Iter, typename Obj>
int count_obj(Iter iter1, Iter iter2, Obj &obj){
int count = 0;
for (; iter1 != iter2; iter1++){
if((*iter1) == obj)
count += 1;
}
return count;
}
我的主要:
int main(){
vector<person *> myp;
person a("ted", 21); person b("sun", 100); person c("ted", 21);
myp.push_back(&a);myp.push_back(&b);myp.push_back(&c);
cout<< "occurences for person objects " << count_obj(myp.begin(), myp.end(), a) << '\n';
}
完全错误
3b.cc: In function ‘int count_obj(Iter, Iter, Obj&) [with Iter = __gnu_cxx::__normal_iterator<person**, std::vector<person*> >, Obj = person]’:
3b.cc:61:79: instantiated from here
3b.cc:42:3: error: no match for ‘operator==’ in ‘iter1.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = person**, _Container = std::vector<person*>, __gnu_cxx::__normal_iterator<_Iterator, _Container>::reference = person*&]() == obj’
make: *** [3b] Error 1
我似乎无法弄清楚我收到了这个错误。