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

https://en.cppreference.com/w/cpp/container/set/set constructs the set(public member function)
https://en.cppreference.com/w/cpp/container/set/~set destructs the set(public member function)
https://en.cppreference.com/w/cpp/container/set/operator%3D assigns values to the container(public member function)
https://en.cppreference.com/w/cpp/container/set/get_allocator returns the associated allocator(public member function)

Iterators

https://en.cppreference.com/w/cpp/container/set/begin returns an iterator to the beginning(public member function)
https://en.cppreference.com/w/cpp/container/set/end returns an iterator to the end(public member function)
https://en.cppreference.com/w/cpp/container/set/rbegin returns a reverse iterator to the beginning(public member function)
https://en.cppreference.com/w/cpp/container/set/rend returns a reverse iterator to the end(public member function)

Capacity

https://en.cppreference.com/w/cpp/container/set/empty checks whether the container is empty(public member function)
https://en.cppreference.com/w/cpp/container/set/size returns the number of elements(public member function)
https://en.cppreference.com/w/cpp/container/set/max_size returns the maximum possible number of elements(public member function)

Modifiers

https://en.cppreference.com/w/cpp/container/set/clear clears the contents(public member function)
https://en.cppreference.com/w/cpp/container/set/insert inserts elements(public member function)
https://en.cppreference.com/w/cpp/container/set/erase erases elements(public member function)
https://en.cppreference.com/w/cpp/container/set/swap swaps the contents(public member function)

Lookup