Skip to content

[Edit] C++: sets #7124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
d0dd9bd
[Edit] SQL: DATEDIFF()
mamtawardhani May 21, 2025
9f5c19b
Update datediff.md
mamtawardhani May 21, 2025
c32e9f3
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
4170ba2
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
8325585
Merge branch 'Codecademy:main' into main
mamtawardhani May 26, 2025
8f6f8e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 27, 2025
e4c54e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 28, 2025
7b3b9c0
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
27ecefd
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
0392da4
Merge branch 'Codecademy:main' into main
mamtawardhani May 30, 2025
d550fa7
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 2, 2025
793be7d
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
2f03b61
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
25eb0ab
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
73e0e3b
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 4, 2025
44f4c63
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 5, 2025
545a8da
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 6, 2025
49d85cd
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 9, 2025
f488437
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 10, 2025
9b642e6
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 11, 2025
afb1cf5
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 12, 2025
dc740fb
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 13, 2025
6a579a7
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 16, 2025
7975f75
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 17, 2025
eaf94a7
[Edit] C++: sets
mamtawardhani Jun 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
319 changes: 273 additions & 46 deletions content/cpp/concepts/sets/sets.md
Original file line number Diff line number Diff line change
@@ -1,96 +1,323 @@
---
Title: 'Sets'
Description: 'Sets are associative containers that store unique elements which can be referenced by the value of the element.'
Description: 'Stores unique elements in sorted order with efficient insertion, deletion, and search operations.'
Subjects:
- 'Computer Science'
- 'Game Development'
- 'Web Development'
Tags:
- 'Data Types'
- 'Sets'
- 'Algorithms'
- 'Containers'
- 'Data Structures'
- 'STL'
CatalogContent:
- 'learn-c-plus-plus'
- 'paths/computer-science'
---

**Sets** are associative containers which store unique elements that can be referenced by an element's value. The value, which is itself the key to access an element in the set, is constant. Once assigned it cannot be changed. However, existing values can be removed or new values can be added.
A **set** is an associative container in the C++ Standard Template Library that stores unique elements in a sorted order. Sets automatically maintain their elements in ascending order by default, though this can be customized using a comparison function. Sets provide efficient insertion, deletion, and search operations with logarithmic time complexity.

## Syntax
Sets are commonly used in scenarios where you need to maintain a collection of unique elements with fast lookup capabilities, such as removing duplicates from data, implementing mathematical set operations, maintaining sorted collections, and checking membership efficiently. They are particularly useful in algorithms that require frequent searching and when the order of elements matters.

## Creating a Set

The basic syntax for creating a set is:

```pseudo
set<dataType> setName;
```

**Parameters:**

- `dataType`: The type of elements to be stored in the set (e.g., int, string, char)
- `setName`: The name assigned to the set variable

Sets can also be created with custom comparison functions:

```pseudo
std::set<dataType> setName;
set<dataType, comparatorFunction> setName;
```

A set can be created by using the `set` keyword and declaring a [data type](https://www.codecademy.com/resources/docs/cpp/data-types) and name.
Additional parameters:

- `comparatorFunction`: Optional parameter that defines custom sorting order for elements

## Example
## Example: Basic Set Creation

The example below initiates a set, inserts values into it using the [.insert()](https://www.codecademy.com/resources/docs/cpp/sets/insert) method, and then prints out the set:
This example demonstrates different ways to create and initialize a set:

```cpp
#include <iostream>
#include <set>
using namespace std;

int main() {
// Initiate set
std::set<int> numSet;

// Insert values into set
numSet.insert(25);
numSet.insert(42);
numSet.insert(10);
numSet.insert(19);

// Print out set
std::set<int> :: iterator iter;
for (iter = numSet.begin(); iter != numSet.end(); iter++) {
std::cout<< *iter << " ";
// Creating an empty set
set<int> emptySet;

// Creating a set with initializer list
set<int> numbers = {10, 5, 20, 15, 5, 10};

// Display the set elements
cout << "Set contains: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;

return 0;
}
```

This outputs the following:
The output of this code is:

```shell
10 19 25 42
Set contains: 5 10 15 20
```

By default, values of the set are sorted in ascending order.
The set automatically removes duplicate values (5 and 10 appeared twice) and maintains elements in sorted order.

## Inserting Elements

Elements can be added to a set using the [`insert()`](https://www.codecademy.com/resources/docs/cpp/sets/insert) method. The `insert()` function automatically places elements in their correct sorted position:

## Setting a Different Comparison Function
```cpp
#include <iostream>
#include <set>
using namespace std;

The comparison function can be changed from the default to `std::greater<dataType>` in order to sort the values in descending order.
int main() {
set<int> numbers;

### Syntax
// Insert individual elements
numbers.insert(25);
numbers.insert(10);
numbers.insert(30);
numbers.insert(10); // Duplicate - will not be added

```pseudo
std::set<dataType, std::greater<dataType> > setName;
cout << "Set after insertions: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;

return 0;
}
```

Output of this code is:

```shell
Set after insertions: 10 25 30
```

The duplicate value 10 was automatically ignored, and elements are displayed in sorted order regardless of insertion order.

## Accessing Elements

Unlike arrays or vectors, sets do not support direct index-based access. Elements are accessed using iterators or by checking for existence using the [`find()`](https://www.codecademy.com/resources/docs/cpp/sets/find) method:

```cpp
#include <iostream>
#include <set>
using namespace std;

int main() {
set<int> numbers = {15, 25, 35, 45, 55};

// Access first element using iterator
auto firstElement = numbers.begin();
cout << "First element: " << *firstElement << endl;

// Check if element exists using find()
auto searchResult = numbers.find(35);
if (searchResult != numbers.end()) {
cout << "Element 35 found: " << *searchResult << endl;
} else {
cout << "Element 35 not found" << endl;
}

return 0;
}
```

The output of the code is:

```shell
First element: 15
Element 35 found: 35
```

The `dataType` for the comparison function must match the data type of the `set`.
The `find()` method returns an iterator pointing to the element if found, or `end()` iterator if the element doesn't exist.

### Codebyte Example
## Updating Elements

Setting the previous example's comparison function to `std::greater<int>`:
Sets do not allow modification of existing elements because changing an element's value could disrupt the sorted order. To update an element, you must remove the old value and insert the new one:

```codebyte/cpp
```cpp
#include <iostream>
#include <set>
using namespace std;

int main() {
// Initiate set
std::set<int, std::greater<int> > numSet;
set<int> numbers = {10, 20, 30, 40};

// Insert values into set
numSet.insert(25);
numSet.insert(42);
numSet.insert(10);
numSet.insert(19);
cout << "Original set: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;

// Print set
std::set<int> :: iterator iter;
// To "update" 30 to 35, remove 30 and insert 35
numbers.erase(30);
numbers.insert(35);

for (iter = numSet.begin(); iter != numSet.end(); iter++) {
std::cout<< *iter << " ";
cout << "Updated set: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;

return 0;
}
```

The output of the code is:

```shell
Original set: 10 20 30 40
Updated set: 10 20 35 40
```

The element 30 was removed and 35 was inserted, maintaining the sorted order of the set.

## Deleting Elements

Elements can be removed from a set using the [`erase()`](https://www.codecademy.com/resources/docs/cpp/sets/erase) method, which can remove elements by value or by iterator position:

```cpp
#include <iostream>
#include <set>
using namespace std;

int main() {
set<int> numbers = {100, 200, 300, 400, 500};

cout << "Original set: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;

// Remove element by value
numbers.erase(300);

// Remove element by iterator (first element)
numbers.erase(numbers.begin());

cout << "Set after deletions: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;

return 0;
}
```

The output of the code is:

```shell
Original set: 100 200 300 400 500
Set after deletions: 200 400 500
```

The value 300 was removed directly, and the first element (100) was removed using an iterator.

## Codebyte Example: Student Grade Tracker

This comprehensive example demonstrates a practical application using sets to track unique student grades and perform various operations:

```cpp
#include <iostream>
#include <set>
#include <string>
using namespace std;

int main() {
set<int> uniqueGrades;

// Adding grades from different students
int grades[] = {85, 92, 78, 85, 96, 78, 88, 92, 75, 96};
int numGrades = sizeof(grades) / sizeof(grades[0]);

cout << "Adding grades: ";
for (int i = 0; i < numGrades; i++) {
cout << grades[i] << " ";
uniqueGrades.insert(grades[i]);
}
cout << endl;

// Display unique grades in sorted order
cout << "Unique grades (sorted): ";
for (int grade : uniqueGrades) {
cout << grade << " ";
}
cout << endl;

// Find highest and lowest grades
cout << "Lowest grade: " << *uniqueGrades.begin() << endl;
cout << "Highest grade: " << *uniqueGrades.rbegin() << endl;

// Check if a specific grade exists
int searchGrade = 90;
if (uniqueGrades.find(searchGrade) != uniqueGrades.end()) {
cout << "Grade " << searchGrade << " exists" << endl;
} else {
cout << "Grade " << searchGrade << " does not exist" << endl;
}

// Remove failing grades (below 80)
auto it = uniqueGrades.begin();
while (it != uniqueGrades.end()) {
if (*it < 80) {
it = uniqueGrades.erase(it);
} else {
++it;
}
}

cout << "Passing grades only: ";
for (int grade : uniqueGrades) {
cout << grade << " ";
}
cout << endl;

cout << "Total unique passing grades: " << uniqueGrades.size() << endl;

return 0;
}
```

This example shows how sets automatically handle duplicates, maintain sorted order, and provide efficient operations for real-world data processing scenarios.

## Frequently Asked Questions

### 1. Can sets contain duplicate elements?

No, sets automatically prevent duplicate elements. If you try to insert a duplicate value, the insertion is ignored and the set remains unchanged.

### 2. How are elements ordered in a set?

By default, elements are stored in ascending order using the less-than operator. You can provide a custom comparison function to change the sorting behavior.

### 3. What is the time complexity of set operations?

Most set operations (insert, delete, find) have O(log n) time complexity due to the underlying balanced binary search tree implementation.

### 4. Can I store custom objects in a set?

Yes, but you must either define the less-than operator for your custom class or provide a custom comparison function when declaring the set.

### 5. How do I iterate through a set in reverse order?

Use reverse iterators with `rbegin()` and `rend()`, or iterate from `rbegin()` to `rend()` using a reverse iterator loop.