Create Set & Add Elements
Part of the Logic & Flow section of Coddy's C++ journey — lesson 36 of 56.
Now that you know what a set is, let's learn how to create one and add elements to it. To add elements to a std::set, you use the .insert() method.
Here's how to create an empty set and add elements:
std::set<int> numbers;
numbers.insert(5);
numbers.insert(2);
numbers.insert(8);The most important feature of sets is that they automatically reject duplicates. If you try to insert the same value twice, the set remains unchanged:
numbers.insert(5); // This won't add another 5
numbers.insert(5); // Neither will thisAfter all these insertions, your set will only contain three unique elements: 2, 5, and 8 (automatically sorted). The duplicate attempts to insert 5 are simply ignored, which is exactly what makes sets so useful for maintaining collections of unique data.
Challenge
EasyCreate a program that demonstrates the unique element feature of std::set by adding several integers to a set, including duplicate values, and then displaying the final size to prove that duplicates are automatically ignored.
The following inputs will be provided:
- An integer
nrepresenting the number of integers to insert - Then
nintegers to be inserted into the set
Your program should:
- Create an empty
std::set<int> - Read the number of integers to insert
- Use a loop to read each integer and insert it into the set using the
.insert()method - After all insertions, print the final size of the set using the
.size()method - Print a message showing how many duplicate attempts were ignored
Use the following exact output format:
Set size: [final_size]
Duplicates ignored: [number_of_duplicates]The number of duplicates ignored should be calculated as the difference between the total number of insertion attempts and the final size of the set. This demonstrates that sets automatically maintain uniqueness by rejecting duplicate values, which is their key feature for storing collections of unique elements.
Cheat sheet
To create a set and add elements, use .insert():
std::set<int> numbers;
numbers.insert(5);
numbers.insert(2);
numbers.insert(8);Sets automatically reject duplicates - inserting the same value multiple times only keeps one copy:
numbers.insert(5); // This won't add another 5
numbers.insert(5); // Neither will thisUse .size() to get the number of unique elements in the set.
Try it yourself
#include <iostream>
#include <set>
using namespace std;
int main() {
// Read the number of integers to insert
int n;
cin >> n;
// Create an empty set
set<int> mySet;
// TODO: Write your code here
// Use a loop to read n integers and insert them into the set
// Calculate how many duplicates were ignored
// Output the results
cout << "Set size: " << mySet.size() << endl;
cout << "Duplicates ignored: " << /* calculate duplicates */ << endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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