Set Container

In C++, a set is a container that stores unique elements in a sorted order. It is implemented using a balanced binary search tree, typically a red-black tree, which provides fast insertion, deletion, and searching of elements. Sets are often used in cases where the elements need to be sorted and/or duplicates are not allowed.

image-20240329-173233.png

 

Main Characteristics

  1. Unique Elements: A set does not allow duplicate values.

  2. Ordered: Elements are stored in sorted order.

  3. Key Only: Unlike maps, where you have key-value pairs, a set only stores the keys.

Common Operations

  • Insert: Adds an element to the set. If the element is already present, it does nothing. Complexity: O(log n).

  • Erase: Removes an element from the set by value or by iterator. Complexity: O(log n).

  • Find: Finds an element in the set. If found, returns an iterator to the element; otherwise, returns an iterator to end(). Complexity: O(log n).

  • Size: Returns the number of elements in the set. Complexity: O(1).

  • Clear: Removes all elements from the set. Complexity: O(n).

  • Begin/End: Provide iterators to the beginning and past-the-end elements in the set, allowing for range-based iteration.

Benefits and Drawbacks

Benefits:

  • Ensures uniqueness of elements.

  • Provides efficient insertion, deletion, and search operations.

  • Maintains elements in sorted order.

Drawbacks:

  • Requires additional memory overhead for maintaining the tree structure.

  • Slower than unordered sets for insertion, deletion, and search, if ordering is not needed.

std::set is a powerful container that offers an efficient way to manage unique, sorted elements. It is part of the Standard Library and can be included with the <set> header. If you don't need the elements to be ordered, you might consider using std::unordered_set, which typically provides faster average-time complexity for basic operations.

 

 

 

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