Understanding Sets

Understanding set in C++

What is set?

set is an associative container in the C++ Standard Library that stores unique elements following a specific order. It is implemented as a balanced binary search tree, typically a Red-Black tree. Sets provide fast retrieval, insertion, and deletion of elements.

Why Use set?

  • Uniqueness: Ensures all elements are unique.

  • Ordered Elements: Automatically keeps elements sorted.

  • Efficiency: Provides logarithmic time complexity for search, insert, and delete operations.

Syntax

Here's the basic syntax for creating a std::set:

#include <set> using namespace std; set<ElementType> setName;
  • ElementType: The type of elements stored in the set.

  • setName: The name of the set object.

Common set Functions

insert

Description: Inserts an element into the set.

Syntax:

pair<iterator, bool> insert(const value_type& value);

Example:

#include <iostream> #include <set> using namespace std; int main() { set<int> mySet; mySet.insert(10); mySet.insert(20); mySet.insert(10); // Duplicate, will not be inserted for (const int& val : mySet) { cout << val << " "; } cout << endl; return 0; }

find

Description: Finds an element in the set.

Syntax:

Example:


erase

Description: Removes elements from the set.

Syntax:

Example:


size

Description: Returns the number of elements in the set.

Syntax:

Example:


clear

Description: Removes all elements from the set.

Syntax:

Example:


begin and end

Description: Returns an iterator to the beginning or end of the set.

Syntax:

Example:

2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark