[LeetCode刷题笔记] C++ unordered_set常用操作
在[1]对常用的STL容器进行了概览,笔者在刷题过程中经常需要查询一些STL容器的函数,实为不便,因此在此对STL容器中常用的操作进行笔记。
std::unordered_set<key>
是一种STL提供的无序集合的类,集合的特点就是其中没有任何重复的元素,这个特点非常适合用于纪录某个数据中是否有重复的数据,并且将其挑出来。std::unordered_set
其和std::set
不同的一点是,前者是没有顺序的,而后者会对元素顺序进行排序,也正是因为其没有顺序,无序set的速度要快得多。通常可以在常数时间进行插入和删除。无序set的键值和其内容值是一样的,和map不同的,我们不能修改其内容,但是可以插入元素或者删除元素。
其类声明原型为:
template < class Key, // unordered_set::key_type/value_type
class Hash = hash<Key>, // unordered_set::hasher
class Pred = equal_to<Key>, // unordered_set::key_equal
class Alloc = allocator<Key> // unordered_set::allocator_type
> class unordered_set;
其中最需要注意的其实就是key
的数据类型的指定了。其常用的函数也不多:
find()
查找元素insert()
插入元素erase()
删除元素clear()
清空容器empty()
判断容器是否为空size()
返回容器的大小
我们通过下面的例子学会如何使用无序set:
#include <unordered_set>
using namespace std;
int main() {
unordered_set<int> s = {1,2,3,4};
auto got = s.find(2);
if (got == s.end())
cout << "not found" << endl ;
else
cout << "element" << *got << " is found" << endl;
s.insert(5);
s.erase(5);
s.clear(); // 清空容器
}
Reference
[1]. https://blog.csdn.net/LoseInVain/article/details/104189784