Sahaj.blogs
27 Dec 2023 · StudyPhase 2 · C++

C++ · STL: set

std::set and std::unordered_set for unique elements, insert's return value, and set operations with algorithms.

std::set<T> keeps unique, sorted elements in a tree. std::unordered_set<T> is the hash version.

  • insert(x) returns a pair<iterator, bool>. The bool tells you whether x was new.
  • count(x) is 0 or 1, and works as a membership test.
  • There are no | / & operators like in Python. Union and intersection come from <algorithm> (set_union, set_intersection), and they work on any sorted ranges.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
#include <string>

int main() {
    std::set<std::string> python{"Asha", "Ravi", "Sahaj", "Meet"};
    std::set<std::string> cpp{"Ravi", "Sahaj", "Dev"};

    auto [it, isNew] = python.insert("Ravi");
    std::cout << "Ravi new? " << isNew << ", size " << python.size() << '\n';

    std::set<std::string> both, either;
    std::set_intersection(python.begin(), python.end(), cpp.begin(), cpp.end(),
                          std::inserter(both, both.begin()));
    std::set_union(python.begin(), python.end(), cpp.begin(), cpp.end(),
                   std::inserter(either, either.begin()));

    std::cout << "both:";   for (auto& s : both) std::cout << ' ' << s;
    std::cout << "\neither:"; for (auto& s : either) std::cout << ' ' << s;
    std::cout << "\nDev in python? " << python.count("Dev") << '\n';
}

Output:

Ravi new? 0, size 4
both: Ravi Sahaj
either: Asha Dev Meet Ravi Sahaj
Dev in python? 0

#cpp#stl

Sources

  1. std::set — cppreference.com
  2. std::unordered_set — cppreference.com
  3. std::set_intersection — cppreference.com