LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Modern C++ Programs · Question 10

Refactor an old-style C++ program into modern C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

Rewrite an old-style "find the employee with the highest salary per department" program (raw arrays, NULL, index loops, printf) in modern C++: std::vector of structs, std::map, structured bindings, optional and std::format.

Solution
main.cpp
#include <format>
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <vector>

struct Employee { std::string name, dept; int salary; };

// Modern version: no raw arrays, no NULL, no manual index bookkeeping
std::map<std::string, const Employee*> top_by_dept(const std::vector<Employee>& staff) {
    std::map<std::string, const Employee*> best;
    for (const auto& e : staff)
        if (auto& slot = best[e.dept]; slot == nullptr || e.salary > slot->salary) slot = &e;
    return best;
}

std::optional<int> salary_of(const std::vector<Employee>& staff, std::string_view name) {
    for (const auto& [n, d, s] : staff) if (n == name) return s;
    return std::nullopt;
}

int main() {
    const std::vector<Employee> staff{{"Asha", "IT", 95000}, {"Ravi", "HR", 61000}, {"Meena", "IT", 88000}, {"John", "HR", 64000}, {"Zoya", "Sales", 70000}};
    for (const auto& [dept, e] : top_by_dept(staff))
        std::cout << std::format("{:<6} {:<6} {:>7}\n", dept, e->name, e->salary);
    std::cout << salary_of(staff, "Meena").value_or(0) << ' ' << salary_of(staff, "Dev").has_value() << '\n';
    return 0;
}

Output Verified by compiling and running

HR     John     64000
IT     Asha     95000
Sales  Zoya     70000
88000 0

An if-initialiser binds a reference to the map slot (created as nullptr on first use), structured bindings unpack structs, and optional replaces a "-1 means not found" convention.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links