Edison Lo
Edison Lo

Reputation: 476

replace algorithm c++ invalid operands to binary expression

I am so confused about the error:

error:invalid operands to binary expression ('Record' and 'const Record')

I am unable to understand why my code:

replace(phoneBook.begin(),phoneBook.end(),old_r,new_r) 

will get the error. What means by const Record?

using namespace std;
class Record{
     public:
          string name;
          int number;
};
int main(){


     vector <Record> phoneBook;
     string command;
     while ( cin >> command) {

          if( command == "Update"){ // Handle the Update command
                Record new_r;
                Record old_r;
                int number;
                cin>>new_r.name>>new_r.number;
                vector<Record>::iterator itr;
               for(itr=phoneBook.begin();itr!=phoneBook.end();itr++){
                    if((*itr).name==new_r.name){
                        old_r.number=(*itr).number;
                        old_r.name=(*itr).name;
                    }
               }

                replace(phoneBook.begin(),phoneBook.end(),old_r, new_r);


          }

     }

}

Upvotes: 3

Views: 1379

Answers (3)

A.S.H
A.S.H

Reputation: 29352

The templated std::replace function needs to check each element if it is equal to old_r to decide if it has to be replaced with new_r. This comparison is made using the operator==. Since you did not write such operator, the compiler is not happy.

add the operator== to tour Record class:

class Record {
public:
  string name;
  int number;
  bool operator==(const Record& other) { return name == other.name && number == other.number; }
};

Upvotes: 0

Give Record a operator == and it'll compile. Something like:

class Record{
     public:
      string name;
      int number;
      bool operator==(const Record& rhs){
          if ((this->name==rhs.name) and (this->number==rhs.number))
              return true;
          return false;
      }
};

Upvotes: 4

kcraigie
kcraigie

Reputation: 1262

You need to override the == operator in your Record class, because std::replace uses it to see whether your elements are equal.

Upvotes: 1

Related Questions