如何循环multimap以获取每个键的第一个键值对



例如,如果我有这样的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;
}

之所以有效是因为我们从末尾开始。因此,multimap中的任何重复键都将覆盖map中的前一个键。因为我们从末尾开始,我们应该有第一个键

最新更新