map 是有序的 内部一般是红黑树实现测试
unordered_map 是无序的 内部是hashspa
因此unordered_map 的插入查找删除速度比map快几倍,对数据的顺序没有要求时尽可能用unordered_mapcode
Note:内存
erase的时候 为了保证 迭代器的正确性要么erase(it++); 要么 it=erase(it)element
使用for(const auto &x:mapXX) 遍历的时候 若是循环内存执行了删除插入操做 那么将不会保证结果的正确性get
对于某一个迭代器 以后执行删除插入操做 string
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 也不失效
删除 插入均不会失效 ,对于这个结论,我比较怀疑,多是测试用例问题hash
不过从http://en.cppreference.com/w/cpp/container/map/erase 相关找到了这个疑惑 结论以下:it
erase,删除io
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,插入
对于unorder_map 若是插入致使了 rehashing 那么全部迭代器会失效,不然不会失效。引用不会失效
rehashing只会发生在 插入的新元素 数量 比 n 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不受影响
删除 :被删除的迭代器失效 其余不受影响