Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use boost::foreach with std::map?

Tags:

c++

foreach

boost

I find boost::foreach very useful as it saves me a lot of writing. For example, let's say I want to print all the elements in a list:

std::list<int> numbers = { 1, 2, 3, 4 }; for (std::list<int>::iterator i = numbers.begin(); i != numbers.end(); ++i)    cout << *i << " "; 

boost::foreach makes the code above much simplier:

std::list<int> numbers = { 1, 2, 3, 4 }; BOOST_FOREACH (int i, numbers)    cout << i << " "; 

Much better! However I never figured out a way (if it's at all possible) to use it for std::maps. The documentation only has examples with types such as vector or string.

like image 985
Thomas Bonini Avatar asked Jan 20 '10 19:01

Thomas Bonini


People also ask

Is C++ std::map ordered?

Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.

What is std::map used for?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.


1 Answers

You need to use:

typedef std::map<int, int> map_type; map_type map = /* ... */;  BOOST_FOREACH(const map_type::value_type& myPair, map) {     // ... } 

The reason being that the macro expects two parameters. When you try to inline the pair definition, you introduce a second comma, making the macro three parameters instead. The preprocessor doesn't respect any C++ constructs, it only knows text.

So when you say BOOST_FOREACH(pair<int, int>, map), the preprocessor sees these three arguments for the macro:

1.pair<int
2. int>
3. map

Which is wrong. This is mentioned in the for-each documentation.

like image 123
GManNickG Avatar answered Sep 22 '22 17:09

GManNickG