STL-multimap

2670 ワード

変換元:http://www.cnblogs.com/xiaoka/archive/2011/08/09/2132342.html
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 132 => 21 223 => 31 32