【C++编程】集合 set/multiset 容器基本操作

🔥 特点:set 在元素插入时会自动排序

set 属于关联式容器、底层由二叉树实现
set vs. multiset: 前者不可以包含重复元素;后者可以

步骤零: 使用时需要包含头文件 #include<set>

void printList(list<int> &l) // 逐个元素打印
{
    for (list<int>::iterator i = l.begin(); i!=l.end(); i++)
    {
        cout << *i << endl;
    }
}

💜 set 构造与赋值

// 1. 默认构造
set <int> s1 = {0,1,3,2,4,8,5,6,7,9};  // 会自动排序
set <int> s11;
s11 = s1;  // 赋值 0 1 2 3 4 5 6 7 8 9

// 2. 通过区间构造
set<int> s2(s1.begin(), s1.end());   
    
// 3. 拷贝构造			
set<int> s3(s1); 			

💜 set 插入和删除:inserteraseclear

set <int> s1 = {0,1,3,2,4,8,5,6,7,9};  // 会自动排序

s1.insert(s1.begin(), -1);  // -1 0 1 2 3 4 5 6 7 8 9	- l1.begin() 处插入 -1
s1.erase(s1.begin());  // 0 1 2 3 4 5 6 7 8 9	  		- s1.begin() 处删除,即最小值 -1
s1.erase(5);  // 0 1 2 3 4 6 7 8 9						- 删除值 5
s1.clear();

💜 set 大小获取:emptysize

set <int> s1 = {0,1,3,2,4,8,5,6,7,9};
cout << s1.empty() << endl;     // 0
cout << s1.size() << endl;      // 10

💜 set 元素统计:findcount (set vs. multiset)

set<int> s1 = {0,1,3,2,4,4,4,8,5,6,7,9};
cout << *s1.find(4) << endl;  // 4, find 返回迭代器 set<int>::iterator pos = s1.find(4);
cout << s1.count(4) << endl;  // 1, 非 3 因为 set 中的元素是唯一的

multiset<int> s1 = {0,1,3,2,4,4,4,8,5,6,7,9};
cout << *s1.find(4) << endl;  // 4, find 返回迭代器 multiset<int>::iterator pos = s1.find(4);
cout << s1.count(4) << endl;  // 3,是 3 因为 multiset 中的元素非唯一的

💜 set 元素互换:swap

set <int> s1 = {0,1,3,2,4,8,5,6,7,9};
set <int> s2 = {-0,-1,-2,-3,-4,-5,-6,-7,-8,-9};
s1.swap(s2);
// s1: -9,-8,-7,-6,-5,-4,-3,-2,-1,-0
// s2: 0,1,2,3,4,5,6,7,8,9

💜 set 自定义排序:由大到小示例

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

#include <algorithm>

class my_compare  // 自定义排序 
{
public:
    bool operator()(int v1, int v2)  // 仿函数,重载 () 运算
    {
        return v1 > v2;
    }
};

void printSet(set<int, my_compare> &s) // 逐个元素打印
{
    for(set<int, my_compare>::iterator i = s.begin(); i!=s.end(); i++)
    {
        cout << *i << endl;
    }
}

int main()
{
    set<int, my_compare> s1 = {0,1,3,2,4,4,4,8,5,6,7,9};
    printSet(s1);  // 9 8 7 6 5 4 3 2 1 0
    return 0; 
}

【博客参考链接】
【黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难】

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值