2

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

#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指针,因为第一个是值,第二个是相应的值。有没有办法做到这一点?

4

1 回答 1

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;
}
于 2013-07-15T17:24:16.093 回答