STL源码剖析-关联式容器之hash_set、hash_map、hash_multiset和hash_multimap

一、hash_set

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

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=6  
        cout << "3 count=" << iset.count(3) << endl;//3 count=1  

        iset.insert(3);  
        cout << "size=" << iset.size() << endl;//size=6  
        cout << "3 count=" << iset.count(3) << endl;//3 count=1  

        iset.insert(7);  
        cout << "size=" << iset.size() << endl;//size=7  
        cout << "3 count=" << iset.count(3) << endl;//3 count=1  

        iset.erase(1);  
        cout << "size=" << iset.size() << endl;//size=6  
        cout << "1 count=" << iset.count(1) << endl;//1 count=0  

        hash_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 found  

        it = find(iset.begin(), iset.end(), 1);  
        if (it == iset.end())  
            cout << "1 not found" << endl;//1 not found  

        system("pause");  
        return 0;  
    }  

二、hash_map

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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值