c++ set<> of class objects. Using own comparer

2019-09-01 06:20发布

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.

2条回答
Emotional °昔
2楼-- · 2019-09-01 07:04

LessComparer needs to implement operator() not operator<

bool operator()( const data& a1, const data& a2 ) const
查看更多
三岁会撩人
3楼-- · 2019-09-01 07:15

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 ){
   //...
}
查看更多
登录 后发表回答