C++STLset basic concepts and usage

Basic concepts of C++STLset

* 所有元素都会在插入时自动被排序

Essence:
set/multiset belongs to associative container, and the underlying structure is realized by binary tree.

The difference between set and multiset:

set does not allow duplicate elements in the container

multiset allows duplicate elements in the container

set construction and assignment

Description: Create a container and set the assignment
structure:

set<T>st;                  //默认构造函数

set(const set &st);    //拷贝构造函数

Assignment:

set& operator=(const set &st);      //重载等号操作符

Code example:

#include<iostream>
#include<set>
using namespace std;
void printSet(set<int>&s)
{
    
    
       for (set<int>::iterator it = s.begin(); it != s.end(); it++)
       {
    
    
              cout << *it << " ";
       }
       cout << endl;
}
//set容器构造和赋值
void test01()
{
    
    
       set<int>s1;
       //插入数据  只有insert方式
       s1.insert(10);
       s1.insert(20);
       s1.insert(50);
       s1.insert(30);
       s1.insert(40);
       
       //遍历容器
       //set容器特点:所有元素插入时会被自动排序
       //set容器不允许插入重复值
       printSet(s1);
       //拷贝构造
       set<int>s2(s1);
       printSet(s2);
       //赋值
       set<int>s3;
       s3 = s2;
       printSet(s3);
}
int main()
{
    
    
       test01();
       return 0;
}

Summary: The
data inserted by the
set container will be automatically sorted using the insert set container.

Guess you like

Origin blog.csdn.net/gyqailxj/article/details/114625313