tags:

views:

302

answers:

2

When I work with BOOST_FOREACH, there isn't a problem with simple templates as vector. But when I try to iterate through map > for example I need to typedef the element type.

Is there any workaround?

+4  A: 

There is a problem because it is a macro, and therefore cannot handle types containing commas (preprocessor doesn't know about templates).

You can also declare the variable before the loop, see documentation.

std::map<int, double> my_map;

//1)
typedef std::pair<int, double> MyPair;
BOOST_FOREACH(MyPair p, my_map) { ... }

//2)
std::pair<int, double> p;
BOOST_FOREACH(p, my_map) { ... }

Edit:

There is a further complication with std::map in particular: the value_type is not std::pair<Key, Value>, but std::pair<const Key, Value>.

Hence, if you go with the typedef, a more proper way (and the only way if you want to use a reference in the foreach loop) is to use

typedef std::pair<const int, double> MyPair;
//or
typedef std::map<int, double>::value_type MyPair;

BOOST_FOREACH(MyPair& ref, my_map) { ... }

However, that won't work if you want to use a variable declared before the loop, since you can't assign to a std::pair<const int, double> instance later (can't assign to the const field), in which case you can only use pair<int, double> as boost's manual shows.

UncleBens
You should probably make that: std::map<int,double>::value_type
Martin York
+2  A: 

BOOST_FOREACH_PAIR is another option that works well in our experience:

http://lists.boost.org/Archives/boost/2009/09/156345.php

http://lists.boost.org/Archives/boost/2009/09/156366.php

dtw