Using unordered_set in C++
The unordered_set is a type of unordered collection container in the C++ standard library that stores unique elements. It is implemented based on a hash table data structure, providing fast element lookup, insertion, and deletion operations.
Here is how to use the unordered_set:
- Include the header file:
header file needs to be included. - Definition of a container: Using the std::unordered_set template to define an unordered_set object, one can specify the element type and hash function.
#include <unordered_set>
std::unordered_set<int> mySet; // 定义一个存储int类型元素的unordered_set
- add
mySet.insert(10); // 插入元素10
mySet.insert(20); // 插入元素20
- delete
mySet.erase(10); // 删除元素10
- locate
std::unordered_set<int>::iterator it = mySet.find(20);
if (it != mySet.end()) {
// 元素存在
} else {
// 元素不存在
}
- Iterate elements: Traverse all elements in an unordered_set using iterators.
for (std::unordered_set<int>::iterator it = mySet.begin(); it != mySet.end(); ++it) {
// 处理*it
}
The unordered_set also provides some other commonly used member functions, such as empty to check if the unordered_set is empty, size to return the number of elements in the unordered_set, and clear to remove all elements from the unordered_set.
It is important to note that elements in an unordered_set are not ordered. The average time complexity for insertion and searching operations is constant O(1), but in the worst case scenario it may reach linear O(n).