STL unordered_map(hash_map)详解
#include<iostream>
#include<string>
#include<vector>
#include<iterator>
#include<unordered_map>
#include<algorithm>
using namespace std;
//底层为hashtable 不允许键值重复 内部元素不会经过排序
//常用函数
/*
构造函数:
unordered_map(size_type n,const hasher& hf,const key_equal& eql);
unordered_map(InputIterator f,InputIterator l,size_t n,...)//...可省略
成员函数:
T& operator[](const key_type& key);
size_t count(const key_type& key);//计算key键值的元素个数
pair<iterator,bool>insert(const pair<...>);
void insert(InputIterator f,InputIterator f);
pair<iterator,iterator> equal_range(const key_type& key);
//插入key元素但是不改变原来元素的相对位置的可插入范围 end()表示得插入到最后
size_t bucket_count();//桶的个数
size_t bucket_size(size_t n);//桶的大小即桶内装的元素个数
void erase(iterator f,iterator l);
void erase(iterator pos);//删除迭代器处的元素 注意该迭代器会失效
*/
const int len = 6;
template<class Key,class Val>
struct Print
{
void operator()(pair<Key, Val> Pair)
{
cout << "first :" << Pair.first << " second :" << Pair.second << endl;
}
};
int main(void)
{
unordered_map<int, string> Hashmap;
int array[len] = { 5,9,2,4,6,9 };
vector<string> Vec;
Vec.push_back("zhang");
Vec.push_back("li");
Vec.push_back("lu");
Vec.push_back("zhao");
Vec.push_back("zhou");
Vec.push_back("cheng");
pair<int, string> PairArra[6];
for (int i = 0; i < len; ++i)
{
PairArra[i].first = array[i];
PairArra[i].second = Vec[i];
}
Hashmap = unordered_map<int,string>(PairArra,PairArra+len,100);
typedef unordered_map<int, string>::iterator M_ITE;
for_each(Hashmap.begin(),Hashmap.end(),Print<int ,string>());
pair<M_ITE, M_ITE> Range = Hashmap.equal_range(1);
//返回一个范围 元素插入在这个范围中不改变原有的顺序
if (Range.first != Hashmap.end())
{
cout << Range.first->first<<" "<< Range.first->second << ":";
cout << Range.second->first<<" "<< Range.second->second << ":";
}
pair<M_ITE, bool> bInsert = Hashmap.insert(pair<int,string>(3,"memg"));
//与map有关的 插入返回的都是pair,bool表示是否插入成功
if (bInsert.second)
{
cout << "insert success: " << bInsert.first->first
<<" "<<bInsert.first->second <<" "<< endl;
Hashmap.erase(bInsert.first);
}
for_each(Hashmap.begin(), Hashmap.end(), Print<int, string>());
cout << "bucket_count: "<<Hashmap.bucket_count() << endl;;
for (size_t i = 0; i < Hashmap.bucket_count(); ++i)
{
if (0 != Hashmap.bucket_size(i))
{
cout << i << "bucket has: " << Hashmap.bucket_size(i) << "element\n";
}
}
Hashmap.erase(Hashmap.begin(), Hashmap.end());
return 0;
}