4

I am trying to print all the values associated with the particular key in unordered_multiset in C++ but unfortunately, when I run bellow code, I am getting two different outputs in Visual studio and online compiler http://cpp.sh/. Visual Studio gives only 'red' as an output cpp.sh gives only 'green' as an output

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

I am expecting to print both 'red' and 'green' for key 'apple' but I am getting either green or red as an output in cpp.sh and visual studio respectively

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 
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • Read about `std::lower_bound` and `std::upper_bound`. That will give you a pair of iterators that define a range that holds all the matching elements. `find` returns an iterator that points at **one** element with the requested key. That loop over `it->second` loops through the characters in the value field of that one match. – Pete Becker Jun 13 '17 at 01:03
  • @PeteBecker minor note, unordered maps don't have lower_bound or upper_bound, but they do have the similar equal_range – Dave S Jun 13 '17 at 01:41
  • @DaveS -- `std` has `lower_bound` and `upper_bound`. But map's `equal_range` would be faster in general. – Pete Becker Jun 13 '17 at 02:11
  • 1
    @PeteBecker `std::lower_bound` and `std::upper_bound` expect an ordered sequence, which `unordered_multimap` obviously isn't. – Igor Tandetnik Jun 13 '17 at 03:56
  • Whoops, never mind. – Pete Becker Jun 14 '17 at 00:09

1 Answers1

4

As @PeteBecker notes, the call you want is equal_range. Specifically, the member function - not the free function.

(untested code)

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

should do what you want.

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45