来源: unordered_set - C++ Reference
无序存储不同的元素,支持基于值的检索。
值value就是key,规定了每一个元素的唯一性。key不可改变。
unorder_set中排列元素是无序的,但是存储是依靠哈希值,支持基于值的快速检索。
一、constructs
注意:range constructs [first,end)
// constructing unordered_sets
#include <iostream>
#include <string>
#include <unordered_set>
template<class T>
T cmerge (T a, T b) { T t(a); t.insert(b.begin(),b.end()); return t; }
int main ()
{
std::unordered_set<std::string> first; // empty
std::unordered_set<std::string> second ( {"red","green","blue"} ); // init list
std::unordered_set<std::string> third ( {"orange","pink","yellow"} ); // init list
std::unordered_set<std::string> fourth ( second ); // copy
std::unordered_set<std::string> fifth ( cmerge(third,fourth) ); // move
std::unordered_set<std::string> sixth ( fifth.begin(), fifth.end() ); // range
std::cout << "sixth contains:";
for (const std::string& x: sixth) std::cout << " " << x;
std::cout << std::endl;
return 0;
}
运行结果
二、Capacity
1,empty() 判空
2.size()长度
2.max_size()最大值
三、Iterators
begin()
end()
四、element lookup
1.find()
iterator find ( const key_type& k );
搜索容器中值为k的元素,如果找到返回指向该元素的iterator;
如果不在容器中,返回end
// unordered_set::find
#include <iostream>
#include <string>
#include <unordered_set>
int main ()
{
std::unordered_set<std::string> myset = { "red","green","blue" };
std::string input;
std::cout << "color? ";
getline (std::cin,input);
std::unordered_set<std::string>::const_iterator got = myset.find (input);
if ( got == myset.end() )
std::cout << "not found in myset";
else
std::cout << *got << " is in myset";
std::cout << std::endl;
return 0;
}
运行结果: