Cover Image for C++ Set
100 views

C++ Set

The C++ std::set is a container class provided by the Standard Template Library (STL) that represents a sorted set of unique elements. It is part of the C++ Standard Library and is implemented as a self-balancing binary search tree, typically a Red-Black Tree. Here are some key characteristics and operations of std::set:

  1. Uniqueness: Elements in a std::set are unique, meaning that you cannot have duplicate elements. If you attempt to insert a duplicate element, it won’t be added.
  2. Sorting: The elements in a std::set are automatically sorted in ascending order according to their values. You cannot change the order of elements in a std::set.
  3. Balanced Tree: std::set uses a self-balancing binary search tree as its underlying data structure. This ensures efficient insertion, deletion, and search operations, all of which have a logarithmic time complexity.
  4. Iterators: You can use iterators to traverse the elements of a std::set in sorted order. The begin() iterator points to the first element, and the end() iterator points just beyond the last element.
  5. Insertion and Deletion:
  • To insert an element, you can use the insert() member function.
  • To remove an element, you can use the erase() member function. You can specify either an iterator to the element or the value of the element to be removed.
  1. Searching: You can search for elements in a std::set using the find() member function, which returns an iterator pointing to the found element or end() if the element is not present.
  2. Size: You can determine the number of elements in a std::set using the size() member function.
  3. Empty Check: You can check if a std::set is empty using the empty() member function.

Here’s an example of how to use std::set:

C++
#include <iostream>
#include <set>

int main() {
    std::set<int> mySet;

    // Insert elements
    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);

    // Duplicate values are ignored
    mySet.insert(20);

    // Iterate through the set
    for (const int& value : mySet) {
        std::cout << value << " ";
    }
    std::cout << std::endl;

    // Erase an element
    mySet.erase(20);

    // Search for an element
    std::set<int>::iterator it = mySet.find(10);
    if (it != mySet.end()) {
        std::cout << "Found: " << *it << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}

In this example, a std::set is used to store a collection of integers. The elements are automatically sorted, and duplicates are ignored. You can see how to insert, erase, and search for elements in the set.

std::set is a useful container when you need a sorted collection of unique elements, and it provides efficient access and manipulation operations.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS