3 集合set的使用
集合set
一个容器内 有许多元素
四种集合 所使用的函数是一样的
①有序 不重复 set
②有序 重复 multiset
③无序 不重复 unordered_set
④无需 重复 unordered_multiset
如何选择有序无序?
有序 省内存
无序 省时间
set的使用
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<vector>
#include<set>
#include<unordered_set>
using namespace std;
int main() {
//【构造】
//有序 不重复
set<int> set1 = { 1,3,5 };
//有序 重复
multiset<int> set2 = { 1,3,5,1,3,5 };
//无序 不重复
unordered_set<int> set3 = { 2,4,6 };
//无序 重复
unordered_multiset<int> set4 = { 2,4,6,2,4,6 };
//【新增元素】 和动态数组vector类似
set1.insert(2);
//【删除元素】 和动态数组vector类似
set1.erase(2);
//使用【迭代器】 遍历集合
//【end()】表示最后一个元素的后一个位置
set<int>::iterator it;
for (it = set1.begin(); it != set1.end(); it++) {
printf("%d ", *it);
}
//【查找元素位置】find
//找不到 就返回一个【尾后迭代器】说明没有找到
if (set1.find(2) == set1.end()) {
printf("\n不在其中");
}
else {
printf("\n在其中");
}
//【获取元素数量】count
//获取2出现了多少次
printf("\n%d", set2.count(2));
//set元素不允许修改
//要修改元素的话 只能先删除 再插入
return 0;
}
for (it = set1.begin(); it != set1.end(); it++) {
printf("%d ", *it);
}
//【查找元素位置】find
//找不到 就返回一个【尾后迭代器】说明没有找到
if (set1.find(2) == set1.end()) {
printf("\n不在其中");
}
else {
printf("\n在其中");
}
//【获取元素数量】count
//获取2出现了多少次
printf("\n%d", set2.count(2));
//set元素不允许修改
//要修改元素的话 只能先删除 再插入
return 0;
}