mercredi 12 janvier 2022

Unable to use std::vector<>::iterator on a vector of pointers, "no suitable user-defined conversion"

Good evening,

I'm working on a piece of code that used to work perfectly fine using std::set.

However, due to a need of an inherent order between objects, I'm going to have to convert it to a vector.

I'm experiencing some issues with iterating over elements of said vector, whereas everything worked perfectly fine when it was defined as an std::set.

The vector is defined as a property of the following Manager class, as such:

    class Manager : public Citizen {
        std::vector<Employee*> employees;

This Manager class overrides a pure virtual printing method from its parent class with the following signature:

std::ostream& printLong(std::ostream& os) const override;

The method implementation is as following:

    std::ostream& Manager::printLong(std::ostream& os) const {
    // Personal info
    os << this->first_name << " " << this->last_name << endl;
    os << "id - " << this->id_number << " ";
    os << "birth_year - " << this->birth_year << endl;
    os << "Salary: " << this->salary << endl;

    // Do not print employees in case there are none
    if (this->employees.empty()) {
        return os;
    }

    // Employee info
    os << "Employees:" << endl;

    std::vector<Employee*>::iterator i = this->employees.begin();
    while (i != employees.end()) {
        Employee* current_employee = (*i);
        current_employee->printShort(os);
        ++i;
    }
    
    return os;
}

The problematic line is:

        std::vector<Employee*>::iterator i = this->employees.begin();

VSCode throws the following error:

no suitable user-defined conversion from "__gnu_cxx::__normal_iterator<mtm::Employee *const *, std::vector<mtm::Employee *, std::allocator<mtm::Employee *>>>" to "__gnu_cxx::__normal_iterator<mtm::Employee **, std::vector<mtm::Employee *, std::allocator<mtm::Employee *>>>" existsC/C++(312)

Why is this not working? What can I do to fix this?

It's worth mentioning that this is part of a course problem where we're not allowed to use auto.

Alternatively, if using vector is not an option in your opinion, what I'm trying to accomplish is to maintain an order between elements so that I can print them according to how they were added/removed by the user into the list of employees.

Aucun commentaire:

Enregistrer un commentaire