【C++ 學習筆記】:STL-multimap
multimap提供了可以一種可以有重複鍵值的STL map類型。其插入方式和map相似,但是由於可以擁有重複鍵值所以在查找方面有些不同。
查找
1. 直接找到每種鍵值的所有元素的第一個元素的遊標。
通過函數:lower_bound( const keytype& x ), upper_bound( const keytype& x ) 可以找到比指定鍵值x的小的鍵值的第一個元素和比指定鍵值x大的鍵值的第一個元素。返回值爲該元素的遊標。
細節:當到達鍵值x已經是最大時,upper_bound返回的是這個multimap的end遊標。同理,當鍵值x已經是最小了,lower_bound返回的是這個multimap的begin遊標。
2. 指定某個鍵值,進行遍歷
可以使用上面的lower_bound和upper_bound函數進行遊歷,也可以使用函數equal_range。其返回的是一個遊標對。遊標對pair::first是由函數lower_bound得到的x的前一個值,遊標對pair::second的值是由函數upper_bound得到的x的後一個值。
樣例如下:
multimap<int,int> a;
a.insert(pair<int,int>(1,11));
a.insert(pair<int,int>(1,12));
a.insert(pair<int,int>(1,13));
a.insert(pair<int,int>(2,21));
a.insert(pair<int,int>(2,22));
a.insert(pair<int,int>(3,31));
a.insert(pair<int,int>(3,32));
multimap<int,int>::iterator p_map;
pair<multimap<int,int>::iterator, multimap<int,int>::iterator> ret;
for(p_map = a.begin() ; p_map != a.end();)
{
cout<<p_map->first<<" =>";
ret = a.equal_range(p_map->first);
for(p_map = ret.first; p_map != ret.second; ++p_map)
cout<<" "<< (*p_map).second;
cout<<endl;
}
結果:
1 => 11 12 13
2 => 21 22
3 => 31 32