STL容器——unordered_set的用法

0、概述

  • unordered_set容器,可直译为无序 set 容器。即 unordered_set容器和 set 容器很像,唯一的区别就在于 set容器会自行对存储的数据进行排序,而 unordered_set 容器不会。
  • 下面是setmultisetunordered_set之间的差别。
    在这里插入图片描述注意这三种集合的底层实现,他决定了算法的时间复杂度。特别注意multiset其实是数值可重复版本的set
  • 需要添加头文件和命名空间
    #include<vector>
    using namespace std ;
    

1、unordered_set容器初始化

  • 创建空的set
    unordered_set<int> set1;
    
  • 拷贝构造
    unordered_set<int> set2(set1);
    
  • 使用迭代器构造 【常用】
    unordered_set<int> set3(set1.begin(), set1.end());
    
  • 使用数组作为其初值进行构造
    unordered_set<int> set4(arr,arr+5);
    
  • 使用处置列表进行构造
    unordered_set<int> set6 {1,2,10,10};
    

2、unordered_set遍历

  • C11
    for(int x : set1) {
    	cout << x << endl;
    }
    
  • 迭代器 【常用】
    for(unordered_set<int>::iterator it = set1.begin(); it != set1.end(); ++it){
    	cout << *it << end;
    } 
    
  • 下面的遍历方式不正确
    for(int i=0;i<set1.size();i++){
    	cout << set1[i] << endl;
    }
    

3、unordered_set常用函数

  • find() 【常用】
    myset.find(x)功能为:查找x,找到之后返回迭代器,失败则返回myset.end()。注意:unordered_set中数值不可重复,所以被寻找的数只有存在和不存在这两种情况,不可能出现多次。
  • insert() 【常用】
    myset.insert(x)功能为:插入元素x
  • erase()
    myset.erase(x)功能为:删除元素x,成功则返回1,失败则返回0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Elec Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值