C++ - 数据容器之 unordered_set(声明与初始化、插入元素、删除元素、容量查询、遍历元素、查找元素)

一、unordered_set

  • unordered_set 是 C++ STL 中的一个关联容器,它有如下特点
  1. unordered_set 中不允许有重复元素

  2. unordered_set 中,元素不以任何特定顺序存储

  3. 平均情况下,查找、插入、删除都是 O(1) 时间复杂度


二、声明与初始化

#include <iostream>
#include <unordered_set>

using namespace std;

int main() {

	// 空 unordered_set
	unordered_set<int> set1;

	// 初始化 unordered_set
	unordered_set<int> set2 = { 1, 2, 3, 4, 5 };

	return 0;
}

三、插入元素

1、演示
#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

int main() {

	unordered_set<string> uset;

	// 插入单个元素
	uset.insert("apple");

	// 插入多个元素
	uset.insert({ "banana", "orange" });

	return 0;
}
2、注意事项
  • unordered_set 不允许有重复元素
#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

int main()
{
	
	unordered_set<string> uset;

	uset.insert("apple");
	uset.insert("banana");
	uset.insert("orange");
	uset.insert("apple");

	cout << uset.size() << endl;

	return 0;
}
# 输出结果

3

四、删除元素

#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

int main()
{
	unordered_set<string> uset = { "apple", "banana", "orange" };

	cout << "删除元素之前,uset 大小为:" << uset.size() << endl;

	uset.erase("banana");

	cout << "删除元素之后,uset 大小为:" << uset.size() << endl;

	uset.clear();

	cout << "清空元素之后,uset 大小为:" << uset.size() << endl;

	return 0;
}
# 输出结果

删除元素之前,uset 大小为:3
删除元素之后,uset 大小为:2
清空元素之后,uset 大小为:0

五、容量查询

#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

int main() {
	unordered_set<string> uset = { "apple", "banana", "orange" };

	bool isEmpty = uset.empty();
	size_t size = uset.size();
	size_t maxSize = uset.max_size();

	cout << "是否为空:" << isEmpty << endl;
	cout << "大小:" << size << endl;
	cout << "最大大小:" << maxSize << endl;

	return 0;
}
# 输出结果

是否为空:0
大小:3
最大大小:329406144173384850

六、遍历元素

#include <iostream>
#include <unordered_set>
#include <string>

using namespace std;

int main()
{
	unordered_set<string> uset = { "apple", "banana", "orange" };

	// 使用迭代器
	for (auto it = uset.begin(); it != uset.end(); it++) {
		cout << *it << endl;
	}

	cout << "----------" << endl;

	// 使用范围 for 循环
	for (auto& str : uset) {
		cout << str << endl;
	}

	return 0;
}
# 输出结果

apple
banana
orange
----------
apple
banana
orange

七、查找元素

#include <iostream>
#include <unordered_set>

using namespace std;

int main() {
	std::unordered_set<int> numbers = { 1, 2, 3, 4, 5 };

	// 使用 find 方法
	auto it = numbers.find(3);
	if (it != numbers.end()) {
		cout << "Found: " << *it << endl;
	}
	else {
		cout << "Not found" << endl;
	}

	// 使用 count 方法,返回值只能为 1,表示存在,或者 0,表示不存在
	if (numbers.count(4) > 0) {
		std::cout << "Element exists" << std::endl;
	}
}
# 输出结果

Found: 3
Element exists
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值