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

The output:

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

How come the other "U.S." states are not showing up?

I am new to c++, so please explain any "newby" pieces too, if it is not too difficult. This example was taken directly from cplusplus.com (http://www.cplusplus.com/reference/unordered_map/unordered_map/begin/), but modified a bit, as it seems my version of c++ did not match.

有帮助吗?

解决方案

std::unordered_map can only contain one of each key. You want std::unordered_multimap.

其他提示

std::unordered_map can have only unique key, so there is a problem in your section of data structure for your problem.you may take a list<pair<string,string>>

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top