Question 20
Back to Exercise
What is the output of the following C++ program?
#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!