Posts tagged: iterators

Using BOOST_FOREACH for Simpler Iteration

I’m working on a little C++ project at the moment. As part of it I’m trying to learn more about the Boost libraries and do clever things with the STL. I have found myself writing a lot of simple loops that iterate over containers of objects and do simple things like call a method on each object. I get tired of writing iterator code like this, it’s something we end up doing a lot as C++ programmers. The syntax for defining and using iterators can be a little long and it can be a right pain to debug if you make a simple typo.

Enter the BOOST_FOREACH macro. I am aware of the STL for_each() function that uses some fancy binding objects to do all sorts of clever stuff. Boost Bindings extend this and create a really powerful set of tools. The problem with this stuff is that it looks a bit weird and isn’t that easy to understand. While I was reading tutorials I came across BOOST_FOREACH. This simple macro gives us something very similar to the foreach keyword in C#.

Imagine you have a container of objects of class Foo, and you want to call the Bar method on each instance of Foo. Usually I’d write something like this:-

for( vector<Foo>::iterator f = container.begin();
                          f != container.end(); f++ )
{
    f->Bar();
}

The BOOST_FOREACH macro can cut out some of the donkey work by doing all the iterator stuff for us. So here’s the above example using BOOST_FOREACH.

BOOST_FOREACH( Foo &f, container )
{
    f.Bar();
}

I like this alternative because it’s a lot cleaner than the classic version and it will work the same with both STL containers and standard C arrays. You also end up typing less and so inevitably will make less mistakes. It’s not going to work in all circumstances, any code where you want to manipulate the container itself is probably a bit risky, but it makes doing simple stuff a bit easier and leads to better code without having to get bogged down with templates and std::for_each.

Image | WordPress Themes