Introducing std::set
Part of the Logic & Flow section of Coddy's C++ journey — lesson 35 of 56.
A std::set is a container that stores a collection of unique elements in sorted order. Unlike vectors or arrays where you can have duplicate values, a set automatically prevents duplicates and keeps everything organized.
Think of a set like a collection of unique items on your desk - you can't have two identical items in the same spot, and they're naturally arranged in order. This makes sets perfect when you need to ensure no duplicates exist in your data.
To use std::set in your program, you need to include the appropriate header:
#include <set>Here's a simple example of declaring a set:
std::set<int> numbers;This creates an empty set that can hold integers. The set will automatically sort any numbers you add to it and reject duplicates, making it an excellent choice for maintaining collections of unique, ordered data.
Cheat sheet
A std::set is a container that stores unique elements in sorted order, automatically preventing duplicates.
To use std::set, include the header:
#include <set>Declare a set:
std::set<int> numbers;Try it yourself
This lesson doesn't include a code challenge.
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