This is the 10th day of my participation in the More text Challenge. For more details, see more text Challenge

Set the container

1. Basic concepts of set

Different from map and multimap, the set container stores each key-value pair. It requires that key and value must be equal, and the bottom layer is a binary tree.

When you use a set to store key-value pairs, you only need to provide one set of data, such as {‘a’,’b’,’c’}

Like a map, the set itself sorts the stored keys by their size. Since key is the same as value, sorting by key is the same as sorting by value.

In addition, the values of elements in a set cannot be the same as the values of keys in a map.

For beginners, do not try to change the value of an element in a set directly. This may break the order of the elements in a set. The correct way to change the value of an element in a set is to delete the element and then add a modified element.

2. Set basic constructor

#include <iostream>
#include <set>
#include <string>
using namespace std;

void printSet(set<string>&s)
{
    for(set<string>::iterator it = s.begin(a); it ! = s.end(a); it++) { cout<<*it<<"";
    }
    cout<<endl;
}

void test01(a)
{
    // Construct a string set
    set<string> myset;
    // Insert elements into the container
    myset.insert("allen");
    myset.insert("Bob");
    myset.insert("Keylle");
    
    // No matter what the insert order, the results will be installed in AscII order output
    printSet(myset);
    
    // Remove the element with value Bob from the container
    myset.erase("Bob");

    printSet(myset);

    // Initialize a set with another set
    set<string> copySet(myset);
    printSet(copySet);

}

int main(a){
    test01(a);return 0;
    
}
Copy the code

Output results:

Bob Keylle allen 
Keylle allen 
Keylle allen 
Copy the code

3. Basic usage of the set container

(1) the begin ()

Return the first element of a set, using a pointer, such as *myset.begin();

(2) end()

Return the last element of a set, using a pointer, such as *myset.end();

Also note that the begin() and end() functions do not check if the set is empty. It is better to use empty() to check if the set is empty before using them.

(3) clear()

Delete all elements from the set.

(4) empty()

Check whether the set is empty.

(5) max_size()

Returns the maximum number of elements that a set may contain.

(6) the size ()

Returns the number of elements in the current set.

(7) rbegin ()

Returns the same value as end().

(8) rend()

Returns the same value as begin().

(9) count()

Originally used to find the number of occurrences of a certain key value in a set. This is not very useful in a set, because a key can only appear 0 or 1 times in a set, so it becomes a matter of determining whether or not a key has appeared in a set.