user6288375
user6288375

Reputation:

C++ Vector Find() Overloaded operator - Error

I'm receiving an Undefined symbols for architecture error when compiling this.

Have to use a Vector, Find() algorithm, and non-member overloaded operator function.

Some guidance around the error would be appreciated.

  #include <stdio.h>
  #include <iostream>
  #include <stdexcept>
  #include <vector>
  #include <algorithm>
  #include <string>

  using namespace std;

  struct person
  {
     char firstInitial;
     string firstName;

     person(const char fi, const string fn)
     {
        firstInitial = fi;
        firstName = fn;
     };

     char getInitial()
     {
        return firstInitial;
     };

     string getName()
     {
        return firstName;
     };

     bool operator==(const person& r);

  };

  bool operator==(const person& r, const person& x)
  {
     return x.firstInitial == r.firstInitial;
  }



  int main (int argc, char *argv[])
  {
     vector<person> myvector;
     vector<person>::iterator itr;

     myvector.push_back(person('j', "john"));
     myvector.push_back(person('s', "steve"));
     myvector.push_back(person('c', "candice"));

     itr = find (myvector.begin(), myvector.end(), person('s', ""));

     if (itr != myvector.end())
        cout << "First Name: " << itr->getName() << '\n';
     else
        cout << "NOT Found" << '\n';
  }

Upvotes: 0

Views: 810

Answers (2)

Telenoobies
Telenoobies

Reputation: 936

You need to define the comparator outside of your class, not as a member function

class Person
{
  public:
    friend bool operator==(const person &a, const person &b);
}

bool operator==(const person& r, const person& x)
{
     return x.firstInitial == r.firstInitial;
}

And that should work, your program returned "Steve" for me.

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172924

The declaration and definition of operator== don't match. If you want to make it a non-member function, just remove the declaration inside class definition, it makes it a member function.

bool operator==(const person& r);

If you want to make it a member function, you should define it outside the class definition as:

bool person::operator==(const person& r)
{
   ...
}

Upvotes: 1

Related Questions