在C ++中打印std :: unordered_multimap中特定键的多个值

时间:2017-06-13 00:26:21

标签: c++ visual-studio stl online-compilation unordered-multimap

我正在尝试在C ++中打印unordered_multiset中与特定键相关联的所有值,但不幸的是,当我运行下面的代码时,我在Visual Studio和在线编译器http://cpp.sh/中得到两个不同的输出。 Visual Studio只提供红色'作为输出 cpp.sh只提供' green'作为输出

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

int main()
{
    std::unordered_map<std::string, std::string> myumm = {
    { "apple","red" },
    { "apple","green" },
    { "orange","orange" },
    { "strawberry","red" }
    };

    std::cout << "myumm contains:";
    for (auto it = myumm.begin(); it != myumm.end(); ++it)
       std::cout << " " << it->first << ":" << it->second;
    std::cout << std::endl;

    std::cout << "myumm's buckets contain:\n";
    for (unsigned i = 0; i < myumm.bucket_count(); ++i) {
       std::cout << "bucket #" << i << " contains:";
       for (auto local_it = myumm.begin(i); local_it != myumm.end(i); ++local_it)
           std::cout << " " << local_it->first << ":" << local_it->second;
       std::cout << std::endl;
   }
   int x = 0;
   auto pt = myumm.find("apple");
   for (auto it = pt->second.begin(); it != pt->second.end(); ++it) {
       std::cout << *it;


   }
   return 0;
}

我希望同时打印“红色”和“红色”字样。和&#39;绿色&#39;关键&#39; apple&#39;但我分别在cpp.sh和visual studio中输出绿色或红色

myumm contains: orange:orange strawberry:red apple:green apple:red
myumm's buckets contain:
bucket #0 contains:
bucket #1 contains: orange:orange
bucket #2 contains:
bucket #3 contains: strawberry:red apple:green apple:red
bucket #4 contains:
green 

1 个答案:

答案 0 :(得分:1)

正如@PeteBecker所说,你想要的电话是equal_range。具体来说,成员函数 - 不是自由函数。

(未经测试的代码)

auto p = myumm.equal_range("apple");
for (auto it = p.first; it != p.second; ++it)
    std::cout << " " << it->first << ":" << it->second;

应该做你想做的事。