tags:

views:

940

answers:

5

Hi, 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.

+1  A: 

Sure you can. The trick is, however, that a map iterator points to a pair of the key and value. It would look something like this:

typedef std::map<std::string, int> MapType;
MapType myMap;

// ... fill the map...

BOOST_FOREACH(MapType::value_type val, myMap)
{
    std::cout << val.first << ": " << val.second << std::endl;
}
Fred Larson
Well, I tried with `BOOST_FOREACH(int i, map)`, `BOOST_FOREACH(pair<int, int>, map)`, etc. Can you post a working example?
Andreas Bonini
Someone could mention that `BOOST_FOREACH` is a *macro*, and therefore it can't properly deal with the comma in the pair template. This is the reason why everybody is suggesting a typedef.
UncleBens
@UncleBens: I think the typedef just makes it look a whole lot cleaner, even if the macro can handle the comma (not sure whether it can).
Fred Larson
Comma has only one meaning for the preprocessor - argument separator. It is not aware of templates and that a comma that falls between `<>` does not introduce another argument.
UncleBens
@UncleBens: Yes, it looks like you're right. But that wasn't my thought in using the typedef. I think that was the OP's problem all along, although I had no way to know that when I came up with the sample code.
Fred Larson
+14  A: 

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.

GMan
Make that `pair<const int, int>`.
UncleBens
The last edit introduces some misinformation. There is no undefined behavior, since the last two examples won't compile. `std::map` protects its key itself: if you have `map<Key, Value>` then the value type is `pair<const Key, Value>`. Note that it makes the key type const.
UncleBens
Can you edit your answer again? I accidentally rescinded my upvote and now it won't make me recast it unless you edit =p EDIT: oh, cool, I edited it myself and it worked :) +1 regiven!
Andreas Bonini
@Andreas: What timing, I just edited anyway :P @Uncle: I see, I forgot they already did that. I've removed the bit, since it's irrelevant. (Like you say.)
GMan
+1  A: 

Yes:

typedef std::map<std::string,int>    MyMap;

MyMap    myMap;

BOOST_FOREACH(MyMap::value_type loop, myMap)
{ 
       // Stuff
}
Martin York
+2  A: 

It's possible, but it's not really the best way to do things (as I've mentioned a few times before, for_each almost never is, and BOOST_FOREACH is only marginally better). For your first example, I think you'd be better off with:

std::copy(numbers.begin(), numbers.end(), 
          std::ostream_iterator<int>(std::cout, " "));

It works pretty similarly with a map, except that you have to define operator<< for it, since there isn't one already defined:

typedef map<std::string, int>::value_type vt;

std::ostream &operator<<(std::ostream &os, vt &v) { 
    return os << v.first << ": " << v.second;
}

...and once again, std::copy does the job quite nicely:

std::copy(mymap.begin(), mymap.end(), 
          std::ostream_iterator<vt>(std::cout, "\n"));
Jerry Coffin
+1. I agree with you, Jerry, although some might argue that having to define the operator (oops, you have a typo there!) is more trouble than the BOOST_FOREACH.
Fred Larson
@Fred: They can argue that, and to an extremely minimal extent, it's even true. Then again, doing the job right often is a bit more work (at least up-front) than just hacking out something that sort of works.
Jerry Coffin
+4  A: 

I use Boost's Range Ex library which implements some fancy range adaptors for iterating over map keys or values. For instance:

map<int, string> foo;
foo[3] = "three";
foo[7] = "seven";

BOOST_FOREACH(i, foo | map_keys)
   cout << i << "\n";


BOOST_FOREACH(str, foo | map_values)
   cout << str << "\n";
Manuel