【STL源码剖析读书笔记】【第5章】关联式容器之hash_set、hash_map、hash_multiset和hash_multimap

来源:互联网 发布:美蓝漫画无法连接网络? 编辑:程序博客网 时间:2024/05/22 09:03

一、hash_set

1、hash_set以hashtable为底层机制,hash_set的操作几乎都是转调用RB-tree的函数而已。

2、hash_set的元素没有自动排序功能。

3、hash_set的使用方式与set完全相同。

4、测试例子

#include<hash_set>#include<iostream>using namespace std;int main(){int ia[] = { 1, 4, 2, 6, 5, 3 };hash_set<int> iset(begin(ia), end(ia));cout << "size=" << iset.size() << endl; //size=6cout << "3 count=" << iset.count(3) << endl;//3 count=1iset.insert(3);cout << "size=" << iset.size() << endl;//size=6cout << "3 count=" << iset.count(3) << endl;//3 count=1iset.insert(7);cout << "size=" << iset.size() << endl;//size=7cout << "3 count=" << iset.count(3) << endl;//3 count=1iset.erase(1);cout << "size=" << iset.size() << endl;//size=6cout << "1 count=" << iset.count(1) << endl;//1 count=0hash_set<int>::iterator it;for (it = iset.begin(); it != iset.end(); ++it)cout << *it << " "; //4 2 6 5 3 7 没有排序功能cout << endl; it = find(iset.begin(), iset.end(), 3);if (it != iset.end())cout << "3 found" << endl;//3 foundit = find(iset.begin(), iset.end(), 1);if (it == iset.end())cout << "1 not found" << endl;//1 not foundsystem("pause");return 0;}

二、hash_map

1、 hash_map以hashtable为底层机制,hash_map的操作几乎都是转调用RB-tree的函数而已。

2、 hash_map的元素没有自动排序功能。

3、 hash_map的使用方式与map完全相同。

4、 测试例子

#include<hash_map>#include<string>#include<iostream>using namespace std;int main(){hash_map<string, int> mp;mp["Jack"] = 1;mp["John"] = 2;mp["Lily"] = 3;mp["Kate"] = 4;pair<string, int> value("Tom", 5);hash_map<string, int>::iterator it;for (it = mp.begin(); it != mp.end(); ++it)cout << it->first << " " << it->second << endl;cout << mp["Kate"] << endl;it = mp.find("John");if (it != mp.end())cout << "John found" << endl;it->second = 8;cout << mp["John"] << endl;system("pause");return 0;}

三、hash_multiset

hash_multiset的特性及用法和multiset完全相同,唯一的差别在于它的底层机制是hashtable,元素不会被自动排序。

四、hash_multimap

hash_multimap的特性及用法和multimap完全相同,唯一的差别在于它的底层机制是hashtable,元素不会被自动排序。


0 0
原创粉丝点击