Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerSTL Containers ProgramsExample 5 of 10
set-basics.cpp
1#include <iostream>
2#include <set>
3using namespace std;
4
5int main() {
6 // Create set
7 set<int> numbers;
8
9 // Insert elements
10 numbers.insert(5);
11 numbers.insert(2);
12 numbers.insert(8);
13 numbers.insert(1);
14 numbers.insert(5); // Duplicate, will be ignored
15 numbers.insert(3);
16
17 // Display set
18 cout << "Set elements (sorted and unique): ";
19 for (int num : numbers) {
20 cout << num << " ";
21 }
22 cout << endl;
23
24 // Check if element exists
25 if (numbers.find(5) != numbers.end()) {
26 cout << "Element 5 found in set" << endl;
27 }
28
29 // 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;
32
33 // Size
34 cout << "Set size: " << numbers.size() << endl;
35
36 // Erase element
37 numbers.erase(5);
38 cout << "\nAfter erasing 5: ";
39 for (int num : numbers) {
40 cout << num << " ";
41 }
42 cout << endl;
43
44 // Lower and upper bound
45 set<int> s = {1, 2, 3, 5, 7, 9};
46 auto it_low = s.lower_bound(4); // First element >= 4
47 auto it_up = s.upper_bound(6); // First element > 6
48
49 cout << "\nLower bound of 4: " << *it_low << endl;
50 cout << "Upper bound of 6: " << *it_up << endl;
51
52 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. 1

    Insert 5, 2, 8, 1, 5, 3; the second 5 is ignored.

  2. 2

    Print 1 2 3 5 8.

  3. 3

    find(5) succeeds; count(5) = 1, count(10) = 0; size = 5.

  4. 4

    erase(5) → 1 2 3 8.

  5. 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:

Stores unique elements (no duplicates)
Automatically sorted
Fast search operations
Balanced binary search tree implementation

Key Features:

Unique elements only
Automatic sorting
Efficient search (O(log n))
Ordered traversal

Creating Sets

Declaration:

set<int> numbers;

What happens here:

Template: set<dataType>
Initially empty
Elements automatically sorted
Duplicates automatically removed

Inserting Elements

Using insert():

numbers.insert(5);

numbers.insert(2);

numbers.insert(8);

numbers.insert(5); // Duplicate ignored

What happens here:

insert() adds element
Duplicates automatically ignored
Elements automatically sorted
O(log n) time complexity

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:

Returns iterator to found element
Returns end() if not found
O(log n) time complexity
Efficient search

Counting Occurrences

Using count():

int count = numbers.count(5); // Returns 1 or 0

What happens here:

Returns 1 if element exists
Returns 0 if element doesn't exist
For set, always 0 or 1 (unique elements)
O(log n) time complexity

Erasing Elements

Using erase():

numbers.erase(5);

What happens here:

Removes element from set
Maintains sorted order
O(log n) time complexity
Reduces size

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:

lower_bound: first element >= value
upper_bound: first element > value
Useful for range queries
O(log n) time complexity

When to Use Sets

Good fits:

Maintaining unique elements
Sorted collections
Fast search requirements
Removing duplicates
Ordered data storage

Example Scenarios:

Unique ID storage
Sorted data requirements
Fast membership testing
Removing duplicates from data

Important Considerations

Automatic Sorting:

Elements always sorted
Order maintained automatically
Sorted by comparison operator
Cannot change sort order (use custom comparator)

Uniqueness:

Duplicates automatically removed
Each element appears once
Inserting duplicate has no effect

Performance:

Insert: O(log n)
Find: O(log n)
Erase: O(log n)
Balanced binary search tree

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.