C++ bootcamp · Lab 18

Second largest

mediumSets12 minLesson: Sets

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a line of integers and print the second largest distinct value.

A std::set stores unique values in sorted order — perfect when duplicates must collapse first.

Input. Integers separated by spaces (at least two distinct values).

Output. One integer: the second largest distinct value.

Examples

Example 1 — Two 7s collapse to one, so second largest is 4.
Input
4 1 7 7 3
Output
4
Example 2
Input
10 20 30
Output
20
Hint
  1. Read until end of input: while (std::cin >> x) s.insert(x);
  2. A set is sorted ascending — step in from the reverse-begin twice to reach the second largest.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <set>

int main() {
  std::set<int> s;
  int x;
  while (std::cin >> x) s.insert(x);
  auto it = s.rbegin();
  ++it;
  std::cout << *it << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.