unordered_map不打印所有存储桶值

时间:2013-10-16 04:29:38

标签: c++ hashmap iteration unordered-map

#include <string>
#include <iostream>
#include <unordered_map>

using namespace std;

typedef unordered_map<string, string> wordMap;
int main ()
{
  wordMap mymap;

  mymap.insert(make_pair("Australia","Canberra"));
  mymap.insert(make_pair("U.S.","Washington"));
  mymap.insert(make_pair("U.S.","New York"));
  mymap.insert(make_pair("U.S.","Kansas"));
  mymap.insert(make_pair("France","Paris"));

  cout << "mymap contains:";

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

  cout << "mymap's buckets contain:\n";

  for ( unsigned i = 0; i < mymap.bucket_count(); i++) 
  {
    cout << "bucket #" << i << " contains:" << endl;

    for ( auto local_it = mymap.begin(i); local_it != mymap.end(i); local_it++ )
    {           
        cout << " " << local_it->first << ":" << local_it->second;
        cout << endl;
    }
  }

  int x;
  cin >> x;

  return 0;
}

输出:

mymap contains: Australia:Canberra U.S.:Washington France:Paris
mymap's buckets contain:
bucket #0 contains:
bucket #1 contains:
bucket #2 contains:
bucket #3 contains:
bucket #4 contains: France:Paris
bucket #5 contains: Australia:Canberra
bucket #6 contains:
bucket #7 contains: U.S.:Washington

为什么另一个“美国”国家没有出现?

我是c ++的新手,所以如果不是太难,请解释任何“newby”作品。 这个例子直接来自cplusplus.com(http://www.cplusplus.com/reference/unordered_map/unordered_map/begin/),但有点修改,因为我的c ++版本似乎不匹配。

2 个答案:

答案 0 :(得分:1)

std::unordered_map只能包含每个密钥中的一个。你想要std::unordered_multimap

答案 1 :(得分:0)

std::unordered_map只能包含唯一键,因此您的问题数据结构部分存在问题。您可能需要list<pair<string,string>>