[c++]unordered_set

1、unordered_set的介绍

1、无序集是一种容器,它以不特定的顺序存储惟一的元素,并允许根据元素的值快速检索单个元素。
2、在unordered_set中,元素的值同时是唯一标识它的键。键是不可变的,只可增删,不可修改
3、在内部,unordered_set中的元素没有按照任何特定的顺序排序,而是根据它们的散列值组织成桶,从而允许通过它们的值直接快速访问单个元素(平均时间复杂度为常数)。 4、unordered_set容器比set容器更快地通过它们的键访问单个元素,尽管它们在元素子集的范围迭代中通常效率较低。
5、容器中的迭代器至少是前向迭代器。

首先要include这个unordered_set头文件。
#include<unorded_set>

在这里插入图片描述
注意:
一是这个容器是个集合,所以重复插入相同的值是没有效果的。大家可以看到我们这里第7行和第9行插入了2次3,实际上这个集合里也只有1个3,第10行输出的结果是2。
二是find的返回值是一个迭代器(iterator),如果找到了会返回指向目标元素的迭代器,没找到会返回end()。

unordered_set是一个集合,有的时候我们需要一个字典,就是保存一系列key/value对,并且可以按key来查询。比如我们要保存很多同学的成绩,每位同学有一个学号,也有一个分数,我们想按学号迅速查到成绩。这时候我们就可以用unordered_map。

函数声明 功能介绍

begin 返回unordered_set第一个元素的迭代器 end 返回unordered_set最后一个元素下一个位置的迭代器
cbegin 返回unordered_set第一个元素的const迭代器
cend 返回unordered_set最后一个元素下一个位置的const迭代器
insert 向容器中插入键值对
erase 删除容器中的键值对
void clear() 清空容器中有效元素个数

用法示例:

#include <iostream>
#include <unordered_set>
#include <array>
#include <string>
using namespace std;

int main()
{
	unordered_set<string> myset1 = { "yellow", "green", "blue" };
	array<string, 2> myarray = { "black", "white" };
	string mystring = "red";

	myset1.insert(mystring);                        // copy insertion
	myset1.insert(mystring + "dish");                 // move insertion
	myset1.insert(myarray.begin(), myarray.end());  // range insertion
	myset1.insert({ "black", "white" });           // initializer list insertion


	unordered_set<std::string> myset2 =
	{ "USA", "Canada", "France", "UK", "Japan", "Germany", "Italy" };

	myset2.erase(myset2.begin());                    // erasing by iterator
	myset2.erase("France");                         // erasing by key
	myset2.erase(myset2.find("Japan"), myset2.end()); // erasing by range
	
	//capacity
	cout << myset1.size() << endl;
	cout << myset2.size() << endl;
	cout << myset1.empty() << endl;
	cout << myset2.empty() << endl;

	myset1.clear();
	myset2.clear();

	cout << myset1.size() << endl;
	cout << myset2.size() << endl;
	cout << myset1.empty() << endl;
	cout << myset2.empty() << endl;

	system("pause");
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值