C++ std::unordered_map 和重复键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8125643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:02:50  来源:igfitidea点击:

std::unordered_map and duplicate keys

c++stlc++11unordered-map

提问by Bee San

I'm using an stl unordered_map, and I can't seem to get the count method to work. This is my program:

我正在使用 stl unordered_map,但似乎无法使计数方法起作用。这是我的程序:

typedef unordered_map<char, int> Mymap;
int main() 
{
    Mymap m;  

    m.insert(Mymap::value_type('a', 1)); 
    m.insert(Mymap::value_type('b', 2)); 
    m.insert(Mymap::value_type('c', 3)); 
    m.insert(Mymap::value_type('b', 4)); 
    m.insert(Mymap::value_type('b', 5)); 

    cout << m.count('b') << endl;

    return 0; 
} 

The documentation for unordered_map says that unordered_map::count(const Key& k)returns the number of elements with the key k. So I would expect the output here to be 3, whereas the real output is 1. Why?

unordered_map 的文档说unordered_map::count(const Key& k)返回带有 key 的元素数k。所以我希望这里的输出是3,而实际输出是1. 为什么?

回答by James McNellis

An unordered_mapmaintains a 1:1 mapping of key to value, so countwill always return zero or one.

Anunordered_map保持键到值的 1:1 映射,因此count将始终返回零或一。

You need an unordered_multimapif you want to map multiple values to a single key.

你需要的unordered_multimap,如果你要多个值映射到一个关键。

回答by jfs

// g++ -std=c++0x init-unorderedmap.cc && ./a.out
#include <iostream>
#include <unordered_map>

namespace {
  typedef std::unordered_map<char, int> Mymap;
}

int main() {
  using namespace std;

  Mymap m{ {'a', 1}, {'b', 2}, {'c', 3}, {'b', 4}, {'b', 5}};
  cout << m.count('b') << endl;

  unordered_multimap<char, int> mm{ {'b', 4}, {'b', 5}};
  cout << mm.count('b') << endl;
}

Output

输出

1
2