C++ Sets

A set in C++ is a container that stores unique elements following a specific order. It is part of the Standard Template Library (STL) and provides functionalities for managing collections of unique items efficiently.

Key Topics

Overview of Sets

Sets provide several advantages:

  • Automatic sorting of elements.
  • Fast lookup, insertion, and deletion of elements.
  • Guarantees that all elements are unique.

Declaring Sets

To declare a set, include the set header and use the following syntax:

#include 
set mySet;

Common Set Operations

Here are some common operations you can perform on sets:

  • insert(): Adds an element to the set (duplicates are ignored).
  • erase(): Removes an element from the set.
  • find(): Searches for an element in the set.
  • count(): Returns the number of occurrences of an element (either 0 or 1 for sets).
  • empty(): Checks if the set is empty.
  • size(): Returns the number of elements in the set.

Example: Basic Set Operations

#include 
#include 
using namespace std;

int main() {
    set mySet;
    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(10); // Duplicate, will be ignored
    cout << "Set size: " << mySet.size() << endl;
    cout << "Contains 20: " << mySet.count(20) << endl;
    mySet.erase(20);
    cout << "Contains 20 after erase: " << mySet.count(20) << endl;
    return 0;
}

Output:

Set size: 2 Contains 20: 1 Contains 20 after erase: 0

Iterating Over Sets

Sets can be iterated using iterators or range-based for loops. Since sets are ordered, the elements will be accessed in sorted order.

Example: Iterating Over a Set

#include 
#include 
using namespace std;

int main() {
    set mySet = {30, 10, 20, 50, 40};
    cout << "Set elements: ";
    for (int element : mySet) {
        cout << element << " ";
    }
    cout << endl;
    return 0;
}

Output:

Set elements: 10 20 30 40 50

Exercises with Sets

Here are some exercises to practice your understanding of sets:

  • Implement a program to find the union and intersection of two sets.
  • Write a function that checks if a set is a subset of another set.
  • Simulate a simple voting system where each vote is unique.

Key Takeaways

  • Sets are containers that store unique elements in a sorted order.
  • Common operations include inserting, erasing, and searching for elements.
  • Sets provide efficient access and manipulation of collections of unique items.
  • Iterating over sets can be done using iterators or range-based for loops.