Menu
Coddy logo textTech

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 and using a set:

std::set<int> numbers;
numbers.insert(5);
numbers.insert(3);
numbers.insert(8);
numbers.insert(3); // duplicate, will be ignored

// numbers now contains: {3, 5, 8} (sorted, no duplicates)

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.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow