map和unordered_map

map 是有序的 內部一般是紅黑樹實現測試

unordered_map 是無序的 內部是hashspa

因此unordered_map  的插入查找刪除速度比map快幾倍,對數據的順序沒有要求時儘可能用unordered_mapcode

Note:內存

  1. erase的時候 爲了保證 迭代器的正確性要麼erase(it++); 要麼 it=erase(it)element

  2. 使用for(const auto &x:mapXX) 遍歷的時候 若是循環內存執行了刪除插入操做 那麼將不會保證結果的正確性get

  3. 對於某一個迭代器  以後執行刪除插入操做  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,插入

  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不受影響

刪除 :被刪除的迭代器失效 其餘不受影響

相關文章
相關標籤/搜索