I have a set of a custom class and when I'm trying to insert an object of that class, the terminal gives me an error:
#ifndef EMPLOYEE_HH
#define EMPLOYEE_HH
#include <string>
#include <iostream>
#include <set>
#include <iterator>
using namespace std ;
class Employee {
public:
// Constructor
Employee(const char* name, double salary) : _name(name), _salary(salary) {}
// Accessors
const char* name() const { return _name.c_str() ; }
double salary() const { return _salary ; }
// Print functions
void businessCard(ostream& os = cout) const {
os << " ------------------ " << endl
<< " | ACME Corporation | " << endl
<< " ------------------ " << endl
<< " " << name() << endl ;
}
private:
string _name ;
double _salary ;
} ;
class Manager : public Employee{
public:
Manager(const char* name, double salary) : Employee(name, salary) {};
void addSubordinate(Employee& empl){
_subs.insert(empl);
}
const set<Employee*>& listOfSubordinates() const{
return _subs;
}
void businessCard() const{
Employee::businessCard();
set <Employee*>::iterator it=_subs.begin();
cout <<"Managed employees: " <<endl;
while(it!=_subs.end()){
cout <<*it <<endl;
}
}
private:
set <Employee*> _subs;
};
#endif
The addSubordinate() routine:
void addSubordinate(Employee& empl){
_subs.insert(empl);
}
returns this error:
no instance of overloaded function "std::set<_Key, _Compare, _Alloc>::insert [with _Key=Employee *, _Compare=std::less<Employee *>, _Alloc=std::allocator<Employee *>]" matches the argument list
I have tried to overload the operator < as other people suggested in response to similar questions, but that doesn't seem to solve the issue.
CodePudding user response:
You need to define the < operator in the Employee class. The items in a set are always sorted and since you don't have a comparator it won't let you insert an instance of that class. Try something like this:
bool operator<(const Employee& emp){
return salary() < emp.salary();
}
CodePudding user response:
Your set accepts a pointer to an Employee
, but you are trying to insert the object itself.
What you can do is
void addSubordinate(Employee& empl){
_subs.insert(&empl); // This will store the address to the object
}
or accept a pointer itself
void addSubordinate(Employee* empl){
_subs.insert(empl);
}