C++STL之hash_table,hash_map與hash_multimap,hash_set與hash_multiset的使用

學習別人的哈,特此聲明。


hash_table是STL中hash_map 和 hash_set 的內部數據結構,hash_table的插入 / 刪除 / 查找的時間複雜度都爲O(1),
是查找速度最快的一種數據結構,但是hash_table中的數據是無序的,一般也只有在數據不需要排序,
只需要滿足快速查找 / 插入 / 刪除的時候使用hash_table。hash_table的擴展是將原hash_table中的數據摘下來插入
到一個臨時的hash_table中,因爲每個桶都使用list來實現的,因此插入刪除都不存在內存copy,所以也是很高效的,
最後再將臨時hash_table和原來的hash_table(此時已經爲空)交換。
//SGI STL中的map底層以紅黑樹實現,hash_map以hash table實現。
//hash_map不允許插入重新鍵值,hash_multimap允許插入重複鍵值。
//這兩者的關係就像map和multimap的關係。底層的hash table提供的大部分的操作,
//hash_map(hash_multimap)大部分都是直接調用hash table的函數。
//
//hash_multimap和hash_map的區別就像multimap與map的區別一樣,
//hash_multimap的底層機制是基於hash table,它可以存在重複的鍵值,
//所以插入函數使用insert_equal(),hash_multimap和hash_map一樣,容器的內容不自動排序。
#include<iostream>
#include<hash_map>
using namespace std;
//using namespace _gnu_cxx;
int main()
{
    hash_map<char, int, hash<char>, equal_to<char> > m;//char是鍵值類型,int是實值類型。
    m['a'] = 10;
    m['b'] = 2;
    cout << m.size() << endl;//輸出2.
    cout << m.find('a')->second << endl;
    cout << m.count('a') << endl;

    system("pause");
    return 0;
}
/*
hash_set與hash_multiset:
實值就是鍵值
以hashtable爲底層機制,所以幾乎所有的hash_set行爲,都是轉調hashtable的操作行爲。

與set、multiset相比,hash_set、hash_multiset沒有自動排序功能。

hash_set與set一樣,實值就是鍵值。使用方式與set完全相同

插入元素操作採用底層機制hashtable的insert_unique()。
hash_multiset與multiset一樣,鍵值可以重複,使用方式和multiset相同。
插入元素操作採用底層機制hashtable的insert_equal()。

hash_map與hash_multmap:
每一個元素同時擁有實值和鍵值

以hashtable爲底層機制,所以幾乎所有的hash_map行爲,都是轉調hashtable的操作行爲。

與map、multimap相比,hash_map、hash_multimap沒有自動排序功能。

hash_map與map一樣,實值就是鍵值。使用方式與set完全相同

插入元素操作採用底層機制hashtable的insert_unique()。

hash_multimap與multimap一樣,鍵值可以重複,pair<key, value>

插入元素操作採用底層機制hashtable的insert_equal()。
*/

//unordered_map與hash_map是一樣的,unordered_map是C++11的,其他類似


#include<iostream>
#include<unordered_map>
#include<cstring>
using namespace std;
int main()
{
    unordered_map<const char*, int>days;
    days["january"] = 31;
    days["february"] = 28;
    days["march"] = 31;
    days["april"] = 30;
    days["may"] = 30;
    days["june"] = 30;
    cout << "june->" << days["june"] << endl;//30

    unordered_map<const char*, int>::iterator ite1 = days.begin();
    unordered_map<const char*, int>::iterator ite2 = days.end();
    for (; ite1 != ite2; ++ite1)
        cout << ite1->first << " " << ite1->second << endl;

    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章