c++ set<> of class objects. Using own comparer giving error: C2804: binary 'operator <' has too many parameters

旧城冷巷雨未停 提交于 2019-12-13 05:39:18

问题


I wrote a c++ code as follows:

#include<iostream>
#include<string>
#include<set>
using namespace std;

class data{
    int i;
    float f;
    char c;
public:
    data();
    data(int i,float f,char c);
};

data::data(int i,float f,char c){
    this->i=i;
    this->f=f;
    this->c=c;
};

class LessComparer{
    bool operator<( const data& a1, const data& a2 ) const{
        return( a1.i < a2.i ||
            (!(a1.i > a2.i) && (a1.f < a2.f)) ||
            (!(a1.i > a2.i) && !(a1.f > a2.f) && (a1.c < a2.c)));
    }
};

int main(){
    set<data,LessComparer> s;
    set<data,LessComparer>::iterator it;
    s.insert(data(1,1.3,'a'));
    s.insert(data(2,2.3,'b'));
    s.insert(data(3,3.3,'c'));
    if((it=s.find(data(1,1.3,'a'))!=s.end())
        cout<<(*it).i;
    cin.get();
    return 0;
}

On compilation it is giving first error as:

error: C2804: binary 'operator <' has too many parameters

and so many other error in class LessComparer.

I'm new to such overloading. Please help me in correcting the code.

Thanks.


回答1:


LessComparer needs to implement operator() not operator<

bool operator()( const data& a1, const data& a2 ) const



回答2:


If you declare the < operator inside the class, the first parameter will implicitly be this.

To declare it with 2 parameters, you must do so outside the context of the class.

The following compares an object of type LessComparer to an object of type data.

class LessComparer{
    bool operator < ( const data& a2 ) const{
        //...
    }
};

If you want to compare two data objects, declare the operator inside class data or outside the class with two parameters:

class data{
public:
    bool operator < ( const data& a2 ) const{
       //...
    }
};

xor

class data
{
   //...
};
bool operator<( const data& a1, const data& a2 ){
   //...
}


来源:https://stackoverflow.com/questions/9783512/c-set-of-class-objects-using-own-comparer-giving-error-c2804-binary-oper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!