无序多图查找所有值

时间:2013-07-15 17:19:14

标签: c++ unordered-map multimap

我想看看是否有可能看到我们所有的价值观。例如:

#include <iostream>
#include <unordered_map>

using namespace std;


int main () {
    unordered_multimap<string,int> hash;

    hash.emplace("Hello", 12);
    hash.emplace("World", 22);
    hash.emplace("Wofh", 25);
    for (int i = 1; i < 10; i++) {
        hash.emplace("Wofh", i);
    }
    cout << "Hello " << hash.find("Hello")->second << endl;
    cout << "Wofh " << hash.count("Wofh") << endl;
    cout << "Wofh " << hash.find("Wofh")->second << endl;

    return 0;
}

输出结果为:

$ ./stlhash
Hello 12
Wofh 10
Wofh 9

而我希望最后一行显示从25,1,2 ...到9.显然find只需要firstsecond指针,因为第一行是值,第二行是相应的值。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:3)

您需要的操作称为equal_range

来自cplusplus.com的示例:

// unordered_multimap::equal_range
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>

typedef std::unordered_multimap<std::string,std::string> stringmap;

int main ()
{
  stringmap myumm = {
     {"orange","FL"},
     {"strawberry","LA"},
     {"strawberry","OK"},
     {"pumpkin","NH"}
  };

  std::cout << "Entries with strawberry:";
  auto range = myumm.equal_range("strawberry");
  for_each (
    range.first,
    range.second,
    [](stringmap::value_type& x){std::cout << " " << x.second;}
  );

  return 0;
}