Boost logo

Boost :

From: Joe Gottman (jgottman_at_[hidden])
Date: 2005-05-04 18:09:31


I just discovered a very nice interaction between the BOOST_FOREACH and
boost::tuples::tie. Suppose we have a container (such as std::map or
std::multimap) whose values are pairs or tuples. If we want to iterate
through the keys and values of a map, we can predeclare separate variables
for the key and value, then use boost::tuples::tie in the first parameter of
BOOST_FOREACH to initialize them separately. See the below code:

-----begin code
#include <iostream>
#include <map>
#include <string>
#include <boost/tuple/tuple.hpp>
#include <boost/foreach.hpp>

int main()
{
    std::map<int, std::string> theMap;
    theMap[1] = "hello";
    theMap[2] = "world";
    int key;
    std::string value;
    BOOST_FOREACH(boost::tuples::tie(key, value), theMap)
    {
        std::cout << key << " => " << value << "\n";
    }
    return 0;
}

------ end code

This code produces the following output:
1 => hello
2 => world

   It would be nice if I could declare key and value inside the loop, but I
don't think this is possible.

Incidentally, if it's not too late I'd like to vote to ACCEPT BOOST_FOREACH
into boost. I use Perl a lot, and use the Perl foreach loop more than twice
as often as the C-style for loop.

Joe Gottman


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk