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
### C++中 `unordered_set` 的用法 `unordered_set` 是 C++ STL 提供的一种哈希表实现的关联容器,它允许存储唯一的关键字并提供快速查找功能。 `set` 不同的是,`unordered_set` 并不对元素进行排序[^3]。 #### 基本特性 - **唯一性**:`unordered_set` 中的每个元素都是唯一的,不允许重复。 - **无序性**:不像 `set` 使用红黑树来保持有序结构,`unordered_set` 利用哈希函数管理数据分布,因此其内部元素是没有固定顺序的。 - **高效查询**:由于基于哈希表设计,平均情况下可以达到 O(1) 时间复杂度的操作性能(如插入删除查找)。 以下是关于如何使用 `unordered_set` 的详细介绍: --- #### 创建初始化 可以通过多种方式创建和初始化一个 `unordered_set` 对象: ```cpp #include <iostream> #include <unordered_set> using namespace std; int main(){ // 初始化方法一:通过列表初始化 unordered_set<string> uset1 = {"apple", "banana", "cherry"}; // 初始化方法二:逐个插入元素 unordered_set<int> uset2; uset2.insert(1); uset2.insert(2); uset2.insert(3); return 0; } ``` 上述代码展示了两种常见的初始化手段——直接赋值以及动态插入[^1]。 --- #### 插入操作 向 `unordered_set` 添加新项非常直观: ```cpp uset1.insert("grape"); // 单独插入一项 uset1.emplace("orange"); // emplace 和 insert 功能相似,在某些场景下效率更高 ``` 注意,如果尝试插入已存在的键,则该操作会被忽略而不引发错误。 --- #### 删除操作 移除指定元素也很简便: ```cpp if (uset1.erase("banana") > 0){ cout << "'banana' was successfully removed." << endl; } else { cout << "'banana' does not exist in the set." << endl; } ``` 这里需要注意返回值的意义;成功删除时返回受影响的数量,否则为零。 --- #### 查找操作 检查某个特定值是否存在或者获取迭代器指向目标位置均可轻松完成: ```cpp auto it = uset1.find("apple"); if(it != uset1.end()){ cout << *it << " found!" << endl; }else{ cout << "Not Found!" << endl; } // 或者更简洁的方式判断存在否 bool exists = (uset1.count("pear") > 0); cout << boolalpha << exists << endl; ``` 其中 `.find()` 返回对应元素的位置指针,`.count()` 给定关键字计数结果要么是0要么是1因为集合里不会有重复条目。 --- #### 迭代遍历 最后我们来看一下怎样访问整个容器内的所有成员: ```cpp for(const auto& elem : uset1){ cout << elem << ' '; } cout << '\n'; ``` 此循环语句利用范围基表达式逐一打印出每一个项目名称。 --- #### 性能考量及其他注意事项 尽管大多数时候 `unordered_set` 能够带来接近常量时间级别的存取速度优势,但在极端条件下比如糟糕散列冲突率较高情形下也可能退化至线性扫描级别O(n)[^4]。所以实际应用过程中应当合理选取合适的hash function以优化整体表现效果。 另外值得注意的一点就是虽然两者都属于关联型容器范畴之内但是它们之间存在着本质上的差异即是否有内在次序关系这一点决定了各自适用场合的不同之处。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值