如何循环multimap只为每个键获取第一个键值对?

时间:2013-03-07 19:49:10

标签: c++ iteration multimap

例如,如果我有这样的mmap:

alice -> 30
bob -> 23
josh -> 20
josh -> 30
andy -> 40
andy -> 40

只得到这对:

alice -> 30
bob -> 23
josh -> 20
andy -> 40

3 个答案:

答案 0 :(得分:5)

这应该做得尽可能干净,有效:

for(auto it = m.begin(); it != m.end(); it = m.upper_bound(it->first)) {
  std::cout << it->first << ":" << it->second << std::endl;
}

答案 1 :(得分:1)

这是一个简短的答案,但不是最有效的

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;
}

这是有效的,因为我们从最后开始。因此,multimap中的任何重复键都将覆盖map中的上一个键。由于我们从最后开始,我们应该有第一个关键

答案 2 :(得分:0)

也许你需要这个,我使用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;
    }
}

输出:

  

alice - &gt; 30

     

andy - &gt; 40

     

bob - &gt; 23

     

josh - &gt; 30