Loop through equal_range in a boost::unordered_multimap

1.5k Views Asked by At

I am trying to learn how to iterate through the values returned from a boost::unordered_multimap which have the same keys. So, I did this,

boost::unordered_multimap<string, string> sample;

In which I have maybe,

<"one", "1">,

<"one", "11">,

<"two", "2">,

<"three", "3">,

<"three", "3">,

<"three", "33">,

<"three", "333">,

and I try to get the values corresponding to "two" so I did this,

std::pair<boost::unordered_multimap<string, string>::iterator, boost::unordered_multimap<string, string>::iterator> > ret = sample.equal_range("two");

and I iterate through it like,

for(boost::unordered_multimap<string, string>::iterator> it = ret.first ; it != ret.second; it++)
{
    cout<<"The values mapped are : "<<*it->second<<"\n";
}

Would I get the value : 2, since that is the only value that is mapped? Would I get out of the loop the first time? I am trying to get the answer online/on boost documentation, but I havent succeeded. It might be a basic question but I am trying to learn. Any help would be appreciated.

TIA

-R

1

There are 1 best solutions below

6
On

About boost: equal_range(key& vkey):

Usage:

std::pair<iterator, iterator> Equal_Range = Unordered_Map.equal_range("key"); 

Return:

A map table contains all the mapped result by KEY: key. Equal_Range.first represents the first location in the result table, while Equal_Range.second represents the last. Special case: If ONLY one element matched, ret.first point to the location mapped by key, and ret.second point to the last location on original map: which is original_map.last.

So by using equal_range(key& vkey), you already get the result table std::pair<itr1, itr2>, which stores all the mapped results you found, and itr1 is the first location mapped by vkey while itr2 represents the last. So your code works fine:

for(auto Itr = ret.first; Itr != ret.second; ++Itr)
        std::cout << "The values mapped are : " << Itr->second << std::endl;

Test case: key = "three"

The values mapped are : 3
The values mapped are : 3
The values mapped are : 33
The values mapped are : 333