點擊查看Evernote原文。
#@author: gr
#@date: 2014-09-13
#@email: forgerui@gmail.com
Chapter3 關聯容器
Topic 22: 切勿直接修改set
或multiset
中的鍵
修改元素的值可以通過下面五步操作,避免作類型轉換。
struct IDNumberLess : public binary_function<Employee, Employee, bool> {bool operator() (const Employee& lhs, const Employee& rhs){return lhs.idNumber() < rhs.idNumber();}
}
/* 1. 查找要修改的元素 */
set<Employee, IDNumberLess> se;
//...
Employee selectedID;
iterator it = se.find(selectedID);
if (it != se.end()){/* 2. 拷貝元素 */Employee tmp(*it);/* 3. 修改元素值 */tmp.setTitle("hello");/* 4. 刪除原來元素 */se.erase(it++);/* 5. 插入新元素 */se.insert(it, tmp);
}
Topic 23: 考慮用排序的vector
替代關聯容器
Topic 24: 當效率至關重要時,請在map::operator[]
與map::insert
之間謹慎做出選擇。
這一條款說起來很簡單,就是使用map
時,如果是更新操作使用map::operator[]
;如果是插入新值時使用map::insert
。
map<int, Widget> m;
//更新操作,m中含有key為1,使用operator[]
m[1] = 1.5;
//插入操作,不含有key為2的項,不用operator[],使用insert
m.insert(map<int, Widget>::value_type(2, 1.50));
這個問題的起源在于map::operator[]
既可以更新舊值又可以插入新值,但使用map::operator[]
進行插入新值效率很低,他會先調用默認構造函數創建一個默認對象,返回引用,修改其值。
最后也可以自己實現一個函數判斷是更新還是插入,分別調用map::operator[]
和map::insert
。
Topic 25: 熟悉非標準的散列容器
除了標準的STL容器,還可以使用其它渠道的容器,包括hash_set
,hash_multiset
,hash_map
,hash_multimap
。不同的提供方實現的形式也各自不同。
SGI
的實現把元素放在一個單向的鏈表中,Dinkumware
的實現則使用了雙向鏈表,但內存消耗更大。根據自己的實際情況選擇。