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

无序关联式容器,又称哈希容器,与关联式容器类似,使用键值对的方式存储数据。与关联式容器的区别是,关联式容器会对存储的键值对按键大小进行排序,而无序关联式容器则不会。无序关联式容器底层实现采用的时哈希表。无序关联式容器有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 << "    ";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值