Introduction.

std::setis an associative container that contains a sorted set of unique objects of type Key . Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees.

template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;

Before Start

Basic use.

#include <iostream>
#include <set>
#include <string>

int main()
{
    std::set<std::string, std::less<std::string> > s;
    s.insert("hello");
    s.insert("world");

    std::set<std::string, std::less<std::string> >::iterator it;
    for (it = s.begin(); it != s.end(); ++it)
        std::cout << *it << std::endl;
    std::cout << "size: " << s.size() << std::endl;
    for (it = s.begin(); it != s.end();)
    {
        s.erase(it++);
    }
    std::cout << "size: " << s.size() << std::endl;

    return 0;
}
output

hello
world
size: 2
size: 0

<aside> ✏️ Note: It printed only F and G because the set does not take the same multiple values. It only accepts a unique value; we should use Multiset to print the same different value.

</aside>

Why do we use iterator, you can go back to std::map to reading our notes on section basic use.

Template.

Member functions

(constructor) constructs the set(public member function)
(destructor) destructs the set(public member function)
operator= assigns values to the container(public member function)
get_allocator returns the associated allocator(public member function)

Iterators

begin returns an iterator to the beginning(public member function)
end returns an iterator to the end(public member function)
rbegin returns a reverse iterator to the beginning(public member function)
rend returns a reverse iterator to the end(public member function)

Capacity

empty checks whether the container is empty(public member function)
size returns the number of elements(public member function)
max_size returns the maximum possible number of elements(public member function)

Modifiers

clear clears the contents(public member function)
insert inserts elements(public member function)
erase erases elements(public member function)
swap swaps the contents(public member function)

Lookup