Sobes.tech
Junior — Middle

Can you give an example of how the Set data structure is used in programming?

sobes.tech AI

Answer from AI

In C++, the data structure std::set represents a container that stores unique elements in sorted order. Main properties:

  • Elements are unique (duplicates are not allowed).
  • Automatic sorting in ascending order (by default).
  • Fast search, insertion, and deletion (logarithmic complexity).

Example of usage:

#include <iostream>
#include <set>

int main() {
    std::set<int> numbers;
    numbers.insert(3);
    numbers.insert(1);
    numbers.insert(4);
    numbers.insert(1); // will not be added, as 1 already exists

    for (int num : numbers) {
        std::cout << num << " ";
    }
    // Output: 1 3 4

    if (numbers.find(3) != numbers.end()) {
        std::cout << "Number 3 found" << std::endl;
    }

    return 0;
}

std::set is convenient to use when you need to store a set of unique elements with the ability for quick search and ordered traversal.