たとえば、私がそのようなmmapを持っている場合:
alice -> 30
bob -> 23
josh -> 20
josh -> 30
andy -> 40
andy -> 40
このペアのみを取得するには:
alice -> 30
bob -> 23
josh -> 20
andy -> 40
これは、可能な限りクリーンで効果的な方法です。
for(auto it = m.begin(); it != m.end(); it = m.upper_bound(it->first)) {
std::cout << it->first << ":" << it->second << std::endl;
}
ここに短い答えがありますが、最も効率的ではありません
multimap<string, int> mm;
// Add stuff to multimap
// Map with only the first items from multimap
map<string,int> m;
for(auto iter = mm.rbegin(); iter != mm.rend(); ++iter){
m[iter->first] = iter->second;
}
これは、最後から開始するために機能します。したがって、マルチマップ内の重複するキーは、マップ内の前のキーを上書きします。最後から始めるので、最初のキーが必要です
たぶんあなたはこれを必要とします、私はlower_bound
ちょうどアイテムを手に入れていました:
#include <iostream>
#include <map>
#include <string>
#include <set>
using namespace std;
int main()
{
multimap<string, int> m;
m.insert(make_pair("alice", 30));
m.insert(make_pair("bob", 23));
m.insert(make_pair("josh", 30));
m.insert(make_pair("josh", 20));
m.insert(make_pair("andy", 40));
m.insert(make_pair("andy", 40));
set<string> names;
for (multimap<string, int>::const_iterator i = m.begin(); i != m.end(); i++)
names.insert(i->first);
for (set<string>::const_iterator i = names.begin(); i != names.end(); i++)
{
multimap<string, int>::const_iterator j = m.lower_bound(*i);
cout << j->first << " -> " << j->second << endl;
}
}
出力:
アリス->30
andy-> 40
ボブ->23
ジョシュ->30