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.
LessComparer needs to implement operator() not operator<
If you declare the
<
operator inside the class, the first parameter will implicitly bethis
.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 typedata
.If you want to compare two
data
objects, declare the operator insideclass data
or outside the class with two parameters:xor