Set Basics in C++
C++ set basics: unique, sorted values with insert, find, count, and erase, plus lower_bound and upper_bound to find the nearest value. Includes the exact output.
1#include <iostream>2#include <set>3using namespace std;45int main() {6 // Create set7 set<int> numbers;89 // Insert elements10 numbers.insert(5);11 numbers.insert(2);12 numbers.insert(8);13 numbers.insert(1);14 numbers.insert(5); // Duplicate, will be ignored15 numbers.insert(3);1617 // Display set18 cout << "Set elements (sorted and unique): ";19 for (int num : numbers) {20 cout << num << " ";21 }22 cout << endl;2324 // Check if element exists25 if (numbers.find(5) != numbers.end()) {26 cout << "Element 5 found in set" << endl;27 }2829 // Count occurrences (0 or 1 for set)30 cout << "Count of 5: " << numbers.count(5) << endl;31 cout << "Count of 10: " << numbers.count(10) << endl;3233 // Size34 cout << "Set size: " << numbers.size() << endl;3536 // Erase element37 numbers.erase(5);38 cout << "\nAfter erasing 5: ";39 for (int num : numbers) {40 cout << num << " ";41 }42 cout << endl;4344 // Lower and upper bound45 set<int> s = {1, 2, 3, 5, 7, 9};46 auto it_low = s.lower_bound(4); // First element >= 447 auto it_up = s.upper_bound(6); // First element > 64849 cout << "\nLower bound of 4: " << *it_low << endl;50 cout << "Upper bound of 6: " << *it_up << endl;5152 return 0;53}
Sample Output
Set elements (sorted and unique): 1 2 3 5 8
The duplicate 5 was ignored.
Lower bound of 4: 5
First element ≥ 4.
Upper bound of 6: 7
First element > 6.
In this one
- Why a set ignores duplicates
- Why a set always iterates in sorted order
- How count works when values are unique
- What lower_bound and upper_bound return
How it works
- 1
Insert 5, 2, 8, 1, 5, 3; the second 5 is ignored.
- 2
Print 1 2 3 5 8.
- 3
find(5) succeeds; count(5) = 1, count(10) = 0; size = 5.
- 4
erase(5) → 1 2 3 8.
- 5
In {1,2,3,5,7,9}: lower_bound(4) = 5, upper_bound(6) = 7.
Edge cases
Bound past the largest value
s.upper_bound(9)
No element is greater than 9, so it returns end(). Dereferencing that is undefined; compare with end() first.
Erasing a missing value
numbers.erase(42)
Nothing happens and erase returns 0, the number of elements removed.
What's going on
A set keeps unique values in sorted order. Insert a duplicate and nothing happens; insert in any order and it still iterates smallest to largest.
The program inserts 5, 2, 8, 1, 5, 3. The second 5 is ignored, so the set holds 1 2 3 5 8, which is what the loop prints. insert actually returns a pair whose .second is false for a duplicate, if you ever need to know.
find(5) returns an iterator to 5, or end() if it is missing. count(5) is 1 and count(10) is 0; in a set, count can only be 0 or 1. size() is 5.
erase(5) removes the value, leaving 1 2 3 8.
The last part uses a second set, {1, 2, 3, 5, 7, 9}, to show two search tools that only make sense on sorted data. lower_bound(4) returns the first element that is at least 4, which is 5. upper_bound(6) returns the first element strictly greater than 6, which is 7. Neither value is in the set; the bounds find where they would go. If no element qualifies, the result is end() and must not be dereferenced.
Like map, a set is a balanced tree, so insert, find, erase, and both bounds are O(log n).
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <set> is there because it provides set container class. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Sets
Set Concept:
Key Features:
Creating Sets
Declaration:
set<int> numbers;
What happens here:
Inserting Elements
Using insert():
numbers.insert(5);
numbers.insert(2);
numbers.insert(8);
numbers.insert(5); // Duplicate ignored
What happens here:
Result: {1, 2, 3, 5, 8} (sorted, unique)
Finding Elements
Using find():
auto it = numbers.find(5);
if (it != numbers.end()) {
// Element found
}
What happens here:
Counting Occurrences
Using count():
int count = numbers.count(5); // Returns 1 or 0
What happens here:
Erasing Elements
Using erase():
numbers.erase(5);
What happens here:
Lower and Upper Bound
lower_bound():
auto it = s.lower_bound(4); // First element >= 4
upper_bound():
auto it = s.upper_bound(6); // First element > 6
What happens here:
When to Use Sets
Good fits:
Example Scenarios:
Important Considerations
Automatic Sorting:
Uniqueness:
Performance:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
In {1,2,3,5,7,9}, what is *lower_bound(5)?
Pick an answer to check it.
Question 2
After inserting 3, 1, 3, 2, what does size() return?
Pick an answer to check it.
Questions people ask
How do I allow duplicates?
Use multiset; count can then be more than 1.
How do I sort descending?
set<int, greater<int>> s;
Can I change an element in place?
No. Elements are const because changing one would break the order. Erase it and insert the new value.