Как использовать базовые функции на векторе объектов с наследованием C ++ - PullRequest
0 голосов
/ 09 июня 2018

У меня есть class Employee, а класс Intern, полученный из Employee.Я хочу хранить информацию о сотрудниках в vector<> и использовать базовые функции для vector, такие как sort(), find_if и т. Д. Насколько я знаю, я должен использовать указатели.Проблема в том, что я не знаю, как использовать эти функции на vector< * > Вот пример того, что я пытаюсь сделать:

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();
        });
}

РЕДАКТИРОВАТЬ: обновленный код, теперь проблема в том, что объект некажется, не сохраняются в векторе, как я пытаюсь cout << i->getID();

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) {

        auto it = find_if(sourceIntern.begin(), sourceIntern.end(),
                          [&newIntern](const unique_ptr<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);
    for(const auto &i : sourceIntern) {
        cout << i->getID();
    }
}

1 Ответ

0 голосов
/ 09 июня 2018

И std::find_if, и std::sort передадут элементы вектора вашим функторам сравнения, как если бы они были test_func(*iter) или compare_func(*iter1, *iter2).Вы написали свои лямбды, чтобы они принимали const Employee& аргументов, но элементы вектора на самом деле std::unique_ptr<Employee> объекты.

Если вы напишите лямбды, чтобы они принимали правильный тип, это должно работать.(Также обратите внимание, что вам не нужно фиксировать sourceEmployee в лямбда-выражении сравнения, поскольку вы его не используете.)

[&newIntern](std::unique_ptr<Employee>& ptr)
{ return ptr->getID() == newIntern.getID(); }

[](std::unique_ptr<Employee>& left, std::unique_ptr<Employee>& right)
{ return left->getID() < right->ID(); }

Я знаю, что вы пометили вопрос [c ++ 11],но если вы можете использовать C ++ 14 или более позднюю версию, вы можете написать auto& вместо std::unique_ptr<Employee>& в качестве лямбда-параметра.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...