I have defined my class SumClass and trying to use it in a map as shown in the code below. I have defined the required <, = and == operator.
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class SumClass {
public:
int id;
int sum;
SumClass() { id = sum = 0;}
bool operator<(const SumClass& rhs) const{
if( (id < rhs.id) && (sum< rhs.sum)) return true;
else return false;
}
bool operator==(const SumClass& rhs) const{
//if(this == &rhs) return true;
if( (id == rhs.id) && (sum == rhs.sum) ) return true;
else return false;
}
void set(int idd, int summ) { id = idd; sum = summ; }
SumClass& operator=(const SumClass& rhs){
id = rhs.id;
sum = rhs.sum;
return *this;
}
};
void test(){
map<SumClass, int> m;
SumClass temp;
temp.set(0,3);
m[temp] = -1;
temp.set(-1, 3);
m[temp] = -1;
temp.set(-1, 2);
m[temp] = -1;
temp.set(0, 1);
cout << "Test: " << m[temp] << endl;
}
int main(){
test();
}
The output of the code above is: "Test: -1". But the expected output is "Test: 0" as the SumClass element I am trying to find is not present in the map. Can anyone please point what am I doing wrong ?