C++ bootcamp · Lab 19

Unique and sorted

mediumSets10 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, remove duplicates, and print the remaining values sorted ascending on one line.

A std::set does both jobs at once: it rejects duplicates and keeps its contents sorted.

Input. Integers separated by spaces.

Output. The distinct values, ascending, space-separated.

Examples

Example 1 — Duplicates removed, order ascending.
Input
3 1 2 3 1 5
Output
1 2 3 5
Example 2
Input
4 4 4
Output
4
Hint
  1. Insert every value into a std::set<int>.
  2. Iterating the set visits values in ascending order — print each with a trailing space.
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);
  for (int v : s) std::cout << v << " ";
  std::cout << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.