LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Programs · Question 4

Sort employees by several criteria with lambdas in C++ Solution, output & explanation

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

Sort a list of employees three ways using lambdas: by department then salary (descending), by name length, and with a lambda chosen at run time from a map of comparators.

Solution
main.cpp
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <vector>

struct Emp { std::string name, dept; int salary; };
using Cmp = std::function<bool(const Emp&, const Emp&)>;

void print(const std::vector<Emp>& v) { for (const auto& e : v) std::cout << e.name << ' '; std::cout << '\n'; }

int main() {
    std::vector<Emp> e{{"Asha", "IT", 90}, {"Ravi", "HR", 60}, {"Meena", "IT", 75}, {"Dev", "HR", 72}, {"Zoya", "IT", 90}};
    std::map<std::string, Cmp> sorts{
        {"dept,salary", [](const Emp& a, const Emp& b) { return std::tuple(a.dept, -a.salary, a.name) < std::tuple(b.dept, -b.salary, b.name); }},
        {"name length", [](const Emp& a, const Emp& b) { return a.name.size() != b.name.size() ? a.name.size() < b.name.size() : a.name < b.name; }},
        {"salary", [](const Emp& a, const Emp& b) { return a.salary < b.salary; }},
    };
    for (std::string key : {"dept,salary", "name length", "salary"}) {
        auto v = e;
        std::stable_sort(v.begin(), v.end(), sorts.at(key));
        std::cout << key << ": ";
        print(v);
    }
    return 0;
}

Output Verified by compiling and running

dept,salary: Dev Ravi Asha Zoya Meena 
name length: Dev Asha Ravi Zoya Meena 
salary: Ravi Dev Meena Asha Zoya

Negating the salary inside a tuple gives "descending salary" while the rest stays ascending. stable_sort keeps Asha before Zoya when salaries are equal.

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