What is set in C++: Explanation and Usage
set is a container that stores unique elements in a sorted order. It automatically removes duplicates and allows fast lookup, insertion, and deletion of elements.How It Works
A set in C++ works like a special collection that keeps things organized and unique. Imagine a set as a box where you put cards with numbers, but the box only allows one card of each number and always keeps them sorted from smallest to largest. This means if you try to add a card that is already inside, the box ignores it.
Under the hood, set uses a balanced tree structure to keep elements sorted and to quickly find, add, or remove items. This makes operations like checking if a number is in the set very fast, even if the set has many elements.
Example
This example shows how to create a set, add elements, and print them. Notice duplicates are ignored and elements are printed in sorted order.
#include <iostream> #include <set> int main() { std::set<int> numbers; numbers.insert(5); numbers.insert(3); numbers.insert(8); numbers.insert(3); // duplicate, will be ignored for (int num : numbers) { std::cout << num << " "; } return 0; }
When to Use
Use a set when you need to store unique items and want them automatically sorted. It is great for tasks like:
- Removing duplicates from a list of values.
- Checking quickly if an item exists.
- Maintaining a collection of items in order without manual sorting.
For example, if you want to keep track of unique user IDs or unique words in a text, set is a simple and efficient choice.
Key Points
- Unique elements: No duplicates allowed.
- Sorted order: Elements are always sorted.
- Fast operations: Insertion, deletion, and search are efficient.
- Underlying structure: Usually a balanced binary tree.
- Use cases: When uniqueness and order matter.