0
点赞
收藏
分享

微信扫一扫

C++ 无序关联式容器 unordered_map/unordered_set

司马吹风 2022-04-04 阅读 56
c++stl

无序关联式容器,又称哈希容器,与关联式容器类似,使用键值对的方式存储数据。与关联式容器的区别是,关联式容器会对存储的键值对按键大小进行排序,而无序关联式容器则不会。无序关联式容器底层实现采用的时哈希表。无序关联式容器有unordered_map, unordered_multimap, unordered_set, unordered_multiset。

需要注意的是,如果容器内盛放的是自定义的数据结构或数据对象,则必须重写自定义数据对象的equal函数和hash函数。

无序关联式容器 unordered_map

http://c.biancheng.net/view/7231.html

#include <unordered_map>
using namespace std;
template < class Key,                        //键值对中键的类型
class T, //键值对中值的类型
class Hash = hash<Key>, //容器内部存储键值对所用的哈希函数
class Pred = equal_to<Key>, //判断各个键值对键相同的规则
class Alloc = allocator< pair<const Key,T> > // 指定分配器对象的类型
> class unordered_map;

方法同关联式容器map,

//初始化
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.begin());

无序关联式容器 unordered_set

http://c.biancheng.net/view/7250.html

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, map, unordered_map


//自定义数据类型,需要重写哈希函数和比较(相等)函数
struct Node {
int x, y;
Node(int x=0, int 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;
// }
};
//仿函数,相等
struct cmp {
bool operator()(const Node &p1, const Node &p2) const { //需要定义为const函数
return p1.x == p2.x and p1.y == p2.y;
}
};
//仿函数,哈希
struct hashnode {
size_t operator()(const Node& p1) const { //需要定义为const函数
return hash<int>()(p1.x) ^ hash<int>()(p1.y);
}
};

void test_unordered_set2() {
unordered_set<Node, hashnode, cmp> us;
us.insert(Node(2, 2));
us.insert(Node(6, 4));
us.insert(Node(4, 3));
us.insert(Node(9, 1));

if (us.find(Node(2, 2)) != us.end()) {
cout << "find\n";
}
if (us.count(Node(2, 2)) == 1) {
cout << "find\n";
}

for (auto & v: us) {
cout << v.x << " " << v.y << " ";
}
}
举报

相关推荐

0 条评论