map和unordered_map

map 是有序的 内部通常是红黑树实现

unordered_map 是无序的 内部是hash

所以unordered_map  的插入查找删除速度比map快几倍,对数据的顺序没有要求时尽量用unordered_map

Note:

  1. erase的时候 为了保证 迭代器的正确性要么erase(it++); 要么 it=erase(it)

  2. 使用for(const auto &x:mapXX) 遍历的时候 如果循环内存执行了删除插入操作 那么将不会保证结果的正确性

  3. 对于某一个迭代器  之后执行删除插入操作  

unordered_map<int, string> map2;
	map2.insert(pair<int, string>(1, "ARTJSAJSTJ"));
	map2.insert(pair<int, string>(2, "BHWTJUWRTHJSRTJ"));
	map2.insert(make_pair(3, "CHRHEWHEHJT"));
	map2.insert(make_pair(4, "CHRHEWHEHJt"));

	auto it = map2.begin();
	auto itt1 = map2.find(3);

	map2.erase(it);

	cout << (*itt1).second.c_str()<<endl;
	//unorder_map   itt1不会失效
	
	
	
	
	
	
		map<int, string> map1;
		map1.insert(pair<int, string>(1, "ARTJSAJSTJ"));
		map1.insert(pair<int, string>(2, "BHWTJUWRTHJSRTJ"));
		map1.insert(make_pair(3, "CHRHEWHEHJT"));
		map1.insert(make_pair(4, "CHRHEWHEHJt"));

	 
	
	 	auto it1 = map1.begin();
	 
		auto itt = map1.find(3);

		map1.erase(it1);
		cout << (*itt).second.c_str();
		//map 也不失效

删除 插入均不会失效 ,对于这个结论,我比较怀疑,可能是测试用例问题

不过从http://en.cppreference.com/w/cpp/container/map/erase  相关找到了这个疑惑 结论如下:

erase,删除

1.对于unordered_map erase 只对 参数的迭代器会失效,其他迭代器 没影响

原话References and iterators to the erased elements are invalidated. Other iterators and references are not invalidated

2.对于map 一样

原话References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

insert,插入

  1. 对于unorder_map 如果插入导致了 rehashing 那么所有迭代器会失效,否则不会失效。引用不会失效

rehashing只会发生在 插入的新元素 数量 比 max_load_factor()*bucket_count(). 大 

原话If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated. Rehashing occurs only if the new number of elements is higher than max_load_factor()*bucket_count(). 

2.对于map  都不会失效

原话No iterators or references are invalidated.


总结:

插入:unordered_map 可能失效,map不受影响

删除 :被删除的迭代器失效 其他不受影响






转载于:https://my.oschina.net/kkkkkkkkkkkkk/blog/653899

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值