今回はmultimapクラスをやります。
mapクラスと何が違うかというと、キーが重複してもかまわないという点です。
multimap<型, 型>オブジェクト名;のように宣言します。
では、サンプルを見てみましょう。
// multimap01.cpp
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
multimap<string, int> mp;
pair<string, int>p;
p.first = "田中";
p.second = 100;
mp.insert(p);
p.first = "田中";
p.second = 95;
mp.insert(p);
p.first = "太田";
p.second = 45;
mp.insert(p);
p.first = "粂井";
p.second = 100;
mp.insert(p);
p.first = "太田";
p.second = 65;
mp.insert(p);
multimap<string, int>::iterator itr;
for (itr = mp.begin(); itr != mp.end(); itr++)
cout << itr->first << "---" << itr->second << endl;
return 0;
}
キーが重複しています。では、実行結果を見てみましょう。
名前でソートされて出力されましたね。
さて、pairクラスをtypedefして、次のように書くこともできます。
// multimap02.cpp
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
multimap<string, int> mp;
typedef pair<string, int>p;
mp.insert(p("境", 45));
mp.insert(p("吉田", 25));
mp.insert(p("境", 35));
mp.insert(p("吉田", 80));
mp.insert(p("粂井", 100));
multimap<string, int>::iterator itr;
for (itr = mp.begin(); itr != mp.end(); itr++)
cout << itr->first << "---" << itr->second << endl;
return 0;
}
実行結果は次のようになります。
Update Jul/04/2004 By Y.Kumei