Recap - Unique Numbers
Part of the Logic & Flow section of Coddy's C++ journey — lesson 40 of 56.
Challenge
EasyCreate a program that reads a series of integers and uses a std::set to automatically filter out duplicates, then prints the count of unique numbers. This demonstrates the primary advantage of sets - maintaining collections of unique elements without manual duplicate checking.
The following inputs will be provided:
- An integer
nrepresenting how many numbers will be entered - Then
nintegers to be processed
Your program should:
- Create an empty
std::set<int> - Read the number of integers that will be entered
- Use a loop to read each integer and insert it into the set using the
.insert()method - After processing all numbers, use the
.size()method to get the count of unique numbers - Print the result showing how many unique numbers were found
Use the following exact output format:
Unique numbers: [count]The set will automatically handle duplicate removal - when you try to insert a number that already exists, the set ignores the duplicate insertion. This means you don't need to manually check for duplicates; simply insert all numbers and let the set maintain uniqueness for you. The final size of the set represents exactly how many distinct numbers were in the input.
Try it yourself
#include <iostream>
#include <set>
using namespace std;
int main() {
// Read the number of integers
int n;
cin >> n;
// Create an empty set to store unique integers
set<int> uniqueNumbers;
// TODO: Write your code here
// Use a loop to read n integers and insert them into the set
// Output the result
cout << "Unique numbers: " << uniqueNumbers.size() << endl;
return 0;
}All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items6Sets (Unique Elements)
Introducing std::setCreate Set & Add ElementsChecking for ElementsRemoving ElementsIterating Over a SetRecap - Unique Numbers