0
#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++ 新手,所以如果不太难的话,也请解释任何“新手”部分。这个例子直接取自 cplusplus.com ( http://www.cplusplus.com/reference/unordered_map/unordered_map/begin/ ),但做了一些修改,因为我的 c++ 版本似乎不匹配。

4

2 回答 2

1

std::unordered_map每个键只能包含一个。你想要std::unordered_multimap

于 2013-10-16T04:36:54.633 回答
0

std::unordered_map只能有唯一键,因此您的问题的数据结构部分存在问题。您可以采取list<pair<string,string>>

于 2013-10-16T04:50:53.967 回答