LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 20

Sorting a copy returned by a getter Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <algorithm>
#include <iostream>
#include <vector>

class Leaderboard {
    std::vector<int> scores_{40, 90, 65};
public:
    std::vector<int> scores() const { return scores_; }       // returns a copy
    std::vector<int> top(std::size_t n) const {
        auto s = scores_;
        std::sort(s.rbegin(), s.rend());
        s.resize(std::min(n, s.size()));
        return s;
    }
};

int main() {
    Leaderboard lb;
    auto all = lb.scores();
    std::sort(all.begin(), all.end());
    auto best = lb.top(2);
    std::cout << all.front() << ' ' << best[0] << ' ' << best[1] << ' ' << lb.scores()[0] << '\n';
    return 0;
}
  • A 40 90 65 40 Correct
  • B 40 90 65 90
  • C 90 40 65 40
  • D 40 90 40 40
Correct Answer: Option A

scores() returns a copy, so sorting it leaves the internal order (40, 90, 65) untouched. top builds its own sorted copy (descending via reverse iterators).

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