Dr.Kameleon
Dr.Kameleon

Reputation: 22820

How to use BOOST_FOREACH with an Unordered_map?

OK, so here's my situation - pretty straightforward but I'm not sure how it can work (I can find no documentation whatsoever...) :

I have an Unordered_map :

typedef unsigned long long U64;
typedef boost::unordered_map<U64, U64> HASH;

And I would like to loop through the elements (mainly the keys), pretty much like using PHP foreach, but this time using BOOST_FOREACH, I suspect something like :

HASH myMap;

// .. assignment, etc...

BOOST_FOREACH (U64 key, myMap)
{
     // do sth with the Key-Value pair

     U64 val = myMap[key];
}

Any ideas?

Upvotes: 1

Views: 3286

Answers (2)

Nathan Buckles
Nathan Buckles

Reputation: 221

Each entry in the Unordered_map will be a pair, so when you use the map in conjuction with BOOST_FOREACH you will iterate over that pair like so:

BOOST_FOREACH( HASH::value_type& v, myMap ) {
    std::cout << "key is " << v.first << " value is " << v.second << std::endl;      
}

Upvotes: 5

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Just solved it :

BOOST_FOREACH(HASH::value_type pair, myMap)
{
     U64 key = pair.first;
     U64 value = pair.second;
}

Upvotes: 0

Related Questions