【C++基礎編程】 #019 STL基本模板庫unordered_set集合基本操作

背景

unordered_set是C++STL基本模板庫中的一個常用的庫。其內部原理也是一個哈希表hashmap,同時插入相同的值是沒有效果的,只記錄不同的值。

基本用法


1. 引入頭文件

#include<unordered_set>

2. 初始化unordered_set

格式unordered_set<type>set;
初始化了一個數據類型爲type的集合set。

// 定義一個名爲set的集合
unordered_set<int>set;

3. 向set集合中插入元素

格式set.insert(number);
向集合中插入數字number。

set.insert(1);		//向set集合中插入元素1
set.insert(3);		//向set集合中插入元素3
set.insert(5);		//向set集合中插入元素5
set.insert(4); 		//向set集合中插入元素4
set.insert(3);		//向set集合中插入元素3

4. 查找set集合中的值

格式if (set.find(key) != set.end()){}


	if (set.find(1) != set.end())
	{
		cout << "找到1啦!" << endl;		//輸出:找到1啦!
	}

	if (set.find(2) != set.end())
	{
		cout << "找到2啦!" << endl;
	}
	else
	{
		cout << "沒有找到2!" << endl;		//輸出:沒有找到2!
	}

5. count()函數用法

格式set.count(key)
若key值在set集合中則輸出1,否則輸出0.

if (set.count(5) == 1)
	{
		cout << "set裏面有5!" << endl;		//輸出:set裏面有5!
	}

	if (set.count(5) == 0)
	{
		cout << "set裏面沒有5!" << endl;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章