vendredi 26 mai 2017

How add/remove to/from vector

I use unique_ptr instead of shared_ptr because it`s not count reference and is faster. You can change it to shared_ptr. My question is how to add/remove properly to/from vector of smart pointers? Key lines are here:

CEO->add(std::move(headSales));
CEO->remove(headSales);

Code:

#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <vector>
#include <memory>
class Employee
{
protected:
    std::string name;
    std::string department;
    std::uint32_t salary;
    std::vector<std::unique_ptr<Employee>> subordinates;

public:
    Employee(std::string n, std::string d, std::uint32_t s) : name(n), department(d), salary(s)
    {}
    bool operator==(const Employee &e)
    {
        return name == e.name && department == e.department && salary == e.salary;
    }
    void add(std::unique_ptr<Employee> e)
    {
        subordinates.push_back(e);
    }
    void remove(const std::unique_ptr<Employee> e)
    {
        subordinates.erase(std::remove(subordinates.begin(), subordinates.end(), e), subordinates.end());
    }
    std::vector<std::unique_ptr<Employee>> getSubordinates() const
    {
        return subordinates;
    }
};
#endif  //EMPLOYEE_H


#include "Employee.h"


int main()
{
    std::unique_ptr<Employee> CEO = std::make_shared<Employee>("John", "CEO", 30000);
    std::unique_ptr<Employee> headSales = std::make_shared<Employee>("Robert", "Head Sales", 20000);
    CEO->add(std::move(headSales));
    CEO->remove(headSales);
}

Aucun commentaire:

Enregistrer un commentaire