Initial Study of set and Multset Containers in C++.

Set and multiset containers

Introduction to set/multiset
set is a collection container in which the elements contained are unique and arranged in a certain order.Element insertion is a sort insertion, so the insertion position cannot be specified.
set is implemented using the data structure of the red-black tree variant, which belongs to the balanced binary tree.Faster insert and delete operations than vector s.
set does not have direct access to elements.(at.(pos) and [] operators are not allowed).
Multset differs from set in that it supports unique key values, where each element value can only occur once, and the same value can occur multiple times in a multiset.
Element values in set or multiset containers cannot be modified directly because they are sorted automatically.If you want to modify an element value, you must delete the original element before inserting a new one.

Header file:
 #include <set>  

set/multiset Default construction of objects
set<int> setInt;            //A set container for int s.
set<float> setFloat;     //A set container for float s.
set<string> setString;     //A set container for string s.
multiset<int> mulsetInt;            //A multi set container for int s.
multi set<float> multisetFloat;     //A multi set container for float s.
multi set<string> multisetString;     //A multi set container for string s.
set Insertion and iterator of set.insert(elem);     //Insert an element into the container.
set.begin();  //Returns the iterator for the first data in the container.
set.end();  //Returns the iterator after the last data in the container.
set.rbegin();  //Returns the iterator of the first to last element in the container.
set.rend();   //Returns the iterator following the last last last element in the container.
set<int> setInt;setInt.insert(3); 
for(set<int>::iterator it=setInt.begin();it!=setInt.end(); ++it){      
    int iItem = *it;      
    cout << iItem;    
    //Or use cout << *it} directly
//This sequentially outputs 123 5.

set.rbegin() and set.rend().Omitted.

Set Sorting the elements of a collection
set<int,less<int> >  setIntA;  //The container is an ascending order of elements. 
set<int,greater<int>> setIntB;   //The container is a descending arrangement of elements.
set<int> Amount to set<int,less<int>>. 
less<int>and greater<int>In int You can change to another type, which mainly follows set Consistent data types are accommodated.

Question 1:less<>and greater<>What is it?
Question 2: If set <> does not contain an int type but contains a custom type, how does the set container sort?
To solve these two problems, you need to know the container's function object, also known as a pseudofunction, called a functor in English.
The following explains what a functor is and how to use it.
Use function object provided by stl

set<int,greater<int>> setIntB;   

The container setIntB now contains elements 5,3,2,1 in order
Usage of function object functor
Although function pointers are widely used to implement function callbacks, C++ also provides an important way to implement callback functions, that is, function objects.
functor, translated as a function object, pseudo-function, operator, is a common class object that overloads the'()'operator.Grammatically, it behaves like a normal function.
Greater<>and less<>are function objects.
Below are some simple implementation principles for greater <int>.
Below are some simple implementation principles for greater <int>.

struct greater{
    bool operator() (const int& iLeft, const int& iRight){       
        return (iLeft>iRight);    //If less <int> is implemented, write return here (iLeft <iRight);

A container is a call to the operator() method of a function object to compare the sizes of two values.
Title: Students with student number and name attributes are now required to insert any number of student objects into the set container so that the students in the container are sorted in ascending order of the student numbers.

 //Student Class
    class CStudent
        CStudent(int iID, string strName)
            m_iID = iID;
            m_strName = strName;
        }     int m_iID; //School Number
        string m_strName; //Name}
        //To keep the topic clear, this class does not write a copy constructor, nor does it require a copy constructor.But you still have to consider the habit of copying constructors.
        //Function object
        struct StuFunctor
            bool operator()  (const CStudent &stu1, const CStudent &stu2)
                return (stu1.m_iID<stu2.m_iID);
        //main function
        void main()
            set<CStudent, StuFunctor> setStu;
            setStu.insert(CStudent(3,"Xiao Zhang"));
            setStu.insert(CStudent(1,"petty thief"));
            setStu.insert(CStudent(2,"Xiao Liu"));
            //The container setStu now contains four student objects: Xiao Li, Xiao Liu, Xiao Zhang, Xiao Wang} set object copy construction and assignment in name order
            set(const set &st);
            //copy constructor
            set& operator=(const set &st);
            //Overloaded equal sign operator
            //Swap two collection containers
            set<int> setIntA;
            set<int> setIntB(setIntA);
            //1 3 5 7 9
            set<int> setIntC;
            setIntC = setIntA;
            //1 3 5 7 9
            //Size of exchange set_
            //Returns the number of elements in the container_
            //Determine if the container is empty
            set<int> setIntA;
            if (!setIntA.empty())
                int iSize = setIntA.size();
                //5}set deletion_
                //Clear all elements_
                //Deletes the element referred to by the pos iterator and returns the iterator for the next element._
                //Delete all elements of the interval [beg, end] and return the iterator of the next element._
                //Delete the element whose value is elem in the container.The element setInt within the deletion interval, declared as a container with set<int>, now contains 1,3,5,6,9,11 elements in sequence.
                set<int>::iterator itBegin=setInt.begin();
                ++ itBegin;
                set<int>::iterator itEnd=setInt.begin();
                ++ itEnd;
                ++ itEnd;
                ++ itEnd;
                //The container setInt now contains 1,6,9,114 elements in sequence.Delete the first element in the container
                setInt.erase(setInt.begin()); //6,9,11 Delete elements with a value of 9 from the container
                //Delete all elements of setInt
                //Find_with empty set container
                //Find the elem element and return an iterator that points to the elem element._
                //Returns the number of elements in a container that have an elem value.For set, either 0 or 1.For multiset, the value may be greater than 1._
                //Returns the iterator for the first >=elem element._
                //  Returns the iterator for the first > elem element._
                //Returns two iterators of the upper and lower bounds of the container equal to the elem.The upper bound is a closed interval and the lower bound is an open interval, such as [beg, end].The above function returns two iterators, which are encapsulated in pairs.The following explains the meaning of pair and how to use it._
                set<int> setInt;
                set<int>::iterator itA = setInt.find(5);
                int iA = *itA;
                //iA == 5int iCount = setInt.count(5); //iCount == 1 set<int>::iterator itB = setInt.lower_bound(5);set<int>::iterator itC = setInt.upper_bound(5);int iB = *itB;
                //iB == 5int iC = *itC; //iC == 7 pair< set<int>::iterator, set<int>::iterator > pairIt = setInt.equal_range(5);
                //What is pair?The use of pair is translated as a group and two values can be considered a unit.Pair <T1,T2>can store two different types of values, such as T1 for int and T2 for float.T1,T2 can also be a custom type.pair.first is the first value in pair and is of type T1.pair.second is the second value in pair and is of type T2.Set <int> setInt;...
                //Insert elements 1,3,5,7,9 into the setInt container
                pair< set<int>::iterator, set<int>::iterator > pairIt = setInt.equal_range(5);
                set<int>::iterator itBeg = pairIt.first;
                set<int>::iterator itEnd = pairIt.second;
                *itEnd == 7

                return 0;

1. Method of using container set/multiset;
Variants of red and black trees, efficient search, insertion can not specify a location, automatic sorting when insertion.
2. Methods of using functor s;
Function-like functions that can be used to customize rules such as element comparison rules.
3. How to use pair.
For groups, a whole unit stores two elements of two types (T1,T2, T1 can be the same as T2).

int x;    
multiset<int> h;//Create a multiset type with the variable name h, the sequence h contains the int type, and the initial h is empty    
    h.insert(x);//Insert x into h        
    scanf("%ld",&x);    }     
pair< multiset<int>::iterator , multiset<int>::iterator > pairIt =h.equal_range(22);
multiset<int>::iterator itBeg = pairIt.first;
multiset<int>::iterator itEnd = pairIt.second; 
int nBeg = *itBeg;int nEnd = *itEnd;     
while(!h.empty()){//The sequence is not empty h.empty()==true indicating that h is empty
    multiset<int>::iterator c = h.begin();//c points to the address of the first element in the h-sequence, the first element being the smallest        
    printf("%ld ",*c);//Data output from address c storage       
    h.erase(c);//Remove the element pointing to c from the h-sequence    

Copyright Statement: This is an original article by CSDN blogger''Battle Programmers'', which follows the CC 4.0 BY-SA copyright agreement. Please attach a link to the original source and this statement.
Original link:

240 original articles have been published. 30 won. 30,000 visits+
Private letter follow

Tags: less

Posted on Fri, 10 Jan 2020 20:53:09 -0500 by trouble706