STL unordered_map(hash_map)详解

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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值