LearnFrenzy
Sign in Take a free test

STL Containers · STL Container Programs · Question 5

Live leaderboard with map and multimap in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Keep player scores in a map (name → score) and a multimap (score → name, descending) in sync while scores update; print the top 3 after the updates.

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

class Leaderboard {
    std::map<std::string, int> score_;
    std::multimap<int, std::string, std::greater<>> ranking_;
public:
    void add(const std::string& name, int points) {
        auto it = score_.find(name);
        int old = it == score_.end() ? 0 : it->second;
        if (it != score_.end()) {                          // remove the old ranking entry
            auto [lo, hi] = ranking_.equal_range(old);
            for (auto r = lo; r != hi; ++r) if (r->second == name) { ranking_.erase(r); break; }
        }
        score_[name] = old + points;
        ranking_.emplace(old + points, name);
    }
    void top(int k) const {
        int rank = 0;
        for (const auto& [s, name] : ranking_) {
            if (rank++ == k) break;
            std::cout << rank << ". " << name << ' ' << s << '\n';
        }
    }
};

int main() {
    Leaderboard lb;
    lb.add("asha", 50); lb.add("ravi", 70); lb.add("meena", 40);
    lb.add("asha", 30); lb.add("john", 75); lb.add("meena", 45);
    lb.top(3);
    return 0;
}

Output Verified by compiling and running

1. meena 85
2. asha 80
3. john 75

The map gives O(log n) lookup by name; the multimap keeps the ranking ordered by score. Each update removes exactly one old ranking entry, keeping both views consistent.

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