1、unordered_set的介绍
1、无序集是一种容器,它以不特定的顺序存储惟一的元素,并允许根据元素的值快速检索单个元素。
2、在unordered_set中,元素的值同时是唯一标识它的键。键是不可变的,只可增删,不可修改
3、在内部,unordered_set中的元素没有按照任何特定的顺序排序,而是根据它们的散列值组织成桶,从而允许通过它们的值直接快速访问单个元素(平均时间复杂度为常数)。 4、unordered_set容器比set容器更快地通过它们的键访问单个元素,尽管它们在元素子集的范围迭代中通常效率较低。
5、容器中的迭代器至少是前向迭代器。
首先要include这个unordered_set头文件。
#include<unorded_set>
注意:
一是这个容器是个集合,所以重复插入相同的值是没有效果的。大家可以看到我们这里第7行和第9行插入了2次3,实际上这个集合里也只有1个3,第10行输出的结果是2。
二是find的返回值是一个迭代器(iterator),如果找到了会返回指向目标元素的迭代器,没找到会返回end()。
unordered_set是一个集合,有的时候我们需要一个字典,就是保存一系列key/value对,并且可以按key来查询。比如我们要保存很多同学的成绩,每位同学有一个学号,也有一个分数,我们想按学号迅速查到成绩。这时候我们就可以用unordered_map。
函数声明 功能介绍
begin 返回unordered_set第一个元素的迭代器 end 返回unordered_set最后一个元素下一个位置的迭代器
cbegin 返回unordered_set第一个元素的const迭代器
cend 返回unordered_set最后一个元素下一个位置的const迭代器
insert 向容器中插入键值对
erase 删除容器中的键值对
void clear() 清空容器中有效元素个数
用法示例:
#include <iostream>
#include <unordered_set>
#include <array>
#include <string>
using namespace std;
int main()
{
unordered_set<string> myset1 = { "yellow", "green", "blue" };
array<string, 2> myarray = { "black", "white" };
string mystring = "red";
myset1.insert(mystring); // copy insertion
myset1.insert(mystring + "dish"); // move insertion
myset1.insert(myarray.begin(), myarray.end()); // range insertion
myset1.insert({ "black", "white" }); // initializer list insertion
unordered_set<std::string> myset2 =
{ "USA", "Canada", "France", "UK", "Japan", "Germany", "Italy" };
myset2.erase(myset2.begin()); // erasing by iterator
myset2.erase("France"); // erasing by key
myset2.erase(myset2.find("Japan"), myset2.end()); // erasing by range
//capacity
cout << myset1.size() << endl;
cout << myset2.size() << endl;
cout << myset1.empty() << endl;
cout << myset2.empty() << endl;
myset1.clear();
myset2.clear();
cout << myset1.size() << endl;
cout << myset2.size() << endl;
cout << myset1.empty() << endl;
cout << myset2.empty() << endl;
system("pause");
return 0;
}