Understanding Sets in C++
Lesson Introduction
Hey there! Today, we're exploring sets in C++ — a useful way to handle collections of unique items. By the end of this lesson, you’ll know how to define sets, add and remove items, check for specific items, and iterate through all the items in a set. Let's dive in!
Understanding Sets in C++
A set in C++ is a container holding unique elements, just like a stamp collection without duplicates. Sets are perfect for tracking unique items without worrying about duplicates — like a class attendance list ensuring no name repeats.
To use sets in C++, include the set library with this line:
Defining a Set
To create an empty set that stores integers, define it like this:
This declares a set named mySet for integers.
Adding Elements
Add elements using the insert function:
If you try to insert 10 again, it won't be added as it’s a duplicate.
However, it won't cause any errors.
Removing Elements
Remove an item with the erase function:
Checking for Elements: `find` Function
Use find to check if an element is in the set. Find is a complex function that returns a thing called iterator pointing to the set's element. We will cover the details of it in the "Intermediate Programming in C++" path. By now, let's just say that if the find method doesn't find the element, it returns a thing which is equal to set.end(), so here is how we can make the comparison:
It works, but seems a bit tricky and hard to remember, right? Let's try out another approach!
