How to use BOOST_FOREACH with an Unordered_map?

家住魔仙堡 提交于 2019-12-11 04:36:53

问题


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?


回答1:


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



回答2:


Just solved it :

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


来源:https://stackoverflow.com/questions/13926534/how-to-use-boost-foreach-with-an-unordered-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!