Question

I have the code below, I'm attempting to write a generic function which takes 2 iterators and an object and checks for any occurrences and returns the number of occurrences.

below my simple class

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

}

Below is the generic function

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

my main:

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

}

Full error

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

I cant seem to figure out I'm getting this error.

Was it helpful?

Solution

You have a vector of person *, and you're trying to compare them against a person. You will need to modify the line of code in count_obj to be either:

if (*(*iter1) == obj)

or:

if ((*iter1) == &obj)

depending on whether you wish to compare pointers or objects.

[Note: Are you aware of the std::count function in the standard library?]

[Note (2): As mentioned in another answer, you should probably read up on "const correctness". You should declare your operator== as const, and it should take a const reference as an argument.]

[Note (3): Storing raw pointers in a container is often a bad idea. For instance, are you aware that you effectively have a memory leak?]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top