samedi 9 juin 2018

How to use basic functions on vector of objects with inheritance C++

I have class Employee, and class Intern which derived from Employee. I want to store Employee information in vector<> and use basic function on vector like sort(), find_if etc. As far as I know, I have to use pointers. The problem is I don't know how to use these functions on vector< * > Here's an example of what I'm trying to do:

vector<unique_ptr<Employee>> Firm;
hireIntern(Firm);
//////////////////////////////

void hireIntern(vector<unique_ptr<Employee>>& sourceIntern) {

    string fillName;
    string fillSurname;
    cout << endl;
    cout << "Enter Intern Name: ";
    cin >> fillName;
    cout << "Enter Intern Surname: ";
    cin >> fillSurname;

    Intern newIntern(fillName, fillSurname);
    newIntern.setID();
    newIntern.Hire();
    newIntern.setSalary(1500);

    while (true) {  /*    1    */

        auto it = find_if(sourceIntern.begin(), sourceIntern.end(),
                          [&newIntern](const Employee &obj) { return obj.getID() == newIntern.getID(); });

        if (it != sourceIntern.end()) {
            newIntern.setID();
        } else {
            break;
        }
    }
    cout << newIntern.getName() << " " << newIntern.getSurname() << " (" << newIntern.getID()
         << ") has been hired" << endl;
    sourceIntern.emplace_back(new Intern());
    sortEmployeeIDs(sourceIntern);
}
              /*     2    */

void sortEmployeeIDs(vector<unique_ptr<Employee>>& sourceEmployee) {
        sort(sourceEmployee.begin(), sourceEmployee.end(), [&sourceEmployee](const Employee &left, const Employee &right) {
                return left.getID() < right.getID();
        });
}

At 1. I get: error: no match for call to ‘(hireIntern(std::vector<std::unique_ptr<Employee> >&)::<lambda(const Employee&)>) (std::unique_ptr<Employee>&)’ { return bool(_M_pred(*__it)); }

At 2. error: no match for call to ‘(sortEmployeeIDs(std::vector<std::unique_ptr<Employee> >&)::<lambda(const Employee&, const Employee&)>) (std::unique_ptr<Employee>&, std::unique_ptr<Employee>&)’ { return bool(_M_comp(*__it1, *__it2)); }

note: no known conversion for argument 1 from ‘std::unique_ptr<Employee>’ to ‘const Employee&’

Aucun commentaire:

Enregistrer un commentaire