Build an organisation chart where managers own reports through shared_ptr and each employee refers back to the manager with weak_ptr; print each person's chain of command and confirm all nodes are freed.
Solution
main.cpp
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Person {
std::string name;
std::weak_ptr<Person> manager;
std::vector<std::shared_ptr<Person>> reports;
static inline int alive = 0;
explicit Person(std::string n) : name(std::move(n)) { ++alive; }
~Person() { --alive; }
};
std::shared_ptr<Person> hire(const std::shared_ptr<Person>& boss, const std::string& name) {
auto p = std::make_shared<Person>(name);
p->manager = boss;
boss->reports.push_back(p);
return p;
}
std::string chain(std::shared_ptr<Person> p) {
std::string s = p->name;
while (auto m = p->manager.lock()) { s += " -> " + m->name; p = m; }
return s;
}
int main() {
{
auto ceo = std::make_shared<Person>("Meera");
auto cto = hire(ceo, "Arjun");
auto dev = hire(cto, "Asha");
hire(cto, "Ravi");
hire(ceo, "Zoya");
std::cout << chain(dev) << '\n' << chain(cto->reports[1]) << '\n';
std::cout << "alive " << Person::alive << '\n';
}
std::cout << "alive " << Person::alive << '\n';
return 0;
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!