将算法c ++替换为二进制表达式的无效操作数

时间:2015-11-05 19:20:44

标签: c++ algorithm replace

我对这个错误很困惑:

  

错误:二进制表达式的操作数无效('记录'和' const记录')

我无法理解为什么我的代码:

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

会收到错误。 const记录是什么意思?

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


          }

     }

}

3 个答案:

答案 0 :(得分:3)

给记录一个运算符==并进行编译。类似的东西:

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

答案 1 :(得分:1)

您需要覆盖Record类中的$(document).on('change', '.report_cause', function () { if ($(this).val() == 'other') { $(this).parent().find('.cause_details').show(); } else { $(this).parent().find('.cause_details').hide(); } }); 运算符,因为std :: replace使用它来查看元素是否相等。

答案 2 :(得分:0)

模板std::replace函数需要检查每个元素是否等于old_r,以确定是否必须将其替换为new_r。使用operator==进行此比较。由于您没有编写此类运算符,编译器不满意。

operator==添加到tour Record类:

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