无序关联式容器,又称哈希容器,与关联式容器类似,使用键值对的方式存储数据。与关联式容器的区别是,关联式容器会对存储的键值对按键大小进行排序,而无序关联式容器则不会。无序关联式容器底层实现采用的时哈希表。无序关联式容器有unordered_map, unordered_multimap, unordered_set, unordered_multiset。
需要注意的是,如果容器内盛放的是自定义的数据结构或数据对象,则必须重写自定义数据对象的equal函数和hash函数,且需要指定其为const函数。
无序关联式容器 unordered_map
template < class Key, //键值对中键的类型
class T, //键值对中值的类型
class Hash = hash<Key>, //容器内部存储键值对所用的哈希函数
class Pred = equal_to<Key>, //判断各个键值对键相同的规则
class Alloc = allocator< pair<const Key,T> > // 指定分配器对象的类型
> class unordered_map;
#include <unordered_map>
using namespace std;
//初始化
unordered_map<string, string> umap;
unordered_map<string, string> umap{{"a", "1"}, {"b", "2"}};
unordered_map<string, string> umap(umap2);
unordered_map<string, string> umap(umap2.begin(), ump2.end());
方法同关联式容器 map~
无序关联式容器 unordered_set
template < class Key, //容器中存储元素的类型
class Hash = hash<Key>, //确定元素存储位置所用的哈希函数
class Pred = equal_to<Key>, //判断各个元素是否相等所用的函数
class Alloc = allocator<Key> //指定分配器对象的类型
> class unordered_set;
#include <unordered_set>
using namespace std;
unordered_set<int> us;
unordered_set<int> us{2, 4, 6};
方法同关联式容器 set~
为自定义对象定义哈希函数
//自定义数据类型,需要重写哈希函数和比较(相等)函数
template<class T>
struct Node {
T x, y;
Node(T x=0, T y=0) : x(x), y(y) {}
friend bool operator== (const Node &p1, const Node &p2) {
return p1.x == p2.x and p1.y == p2.y;
}
};
//仿函数,相等
template<class T>
struct cmp {
bool operator()(const Node<T> &p1, const Node<T> &p2) const { //需要定义为const函数
return p1.x == p2.x and p1.y == p2.y;
}
};
//仿函数,哈希
template<class T>
struct hashnode {
size_t operator()(const Node<T>& p1) const { //需要定义为const函数
return hash<T>()(p1.x) ^ hash<T>()(p1.y);
}
};
void test_unordered_set2() {
unordered_set<Node<int>, hashnode<int>, cmp<int>> us;
us.insert(Node<int>(2, 2));
us.insert(Node<int>(6, 4));
us.insert(Node<int>(4, 3));
us.insert(Node<int>(9, 1));
if (us.find(Node<int>(2, 2)) != us.end()) {
cout << "find\n";
}
if (us.count(Node<int>(2, 2)) == 1) {
cout << "find\n";
}
for (auto & v: us) {
cout << v.x << " " << v.y << " ";
}
}