Using tuples::tie with BOOST_FOREACH

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

Joe Gottman wrote:
int key; std::string value; BOOST_FOREACH(boost::tuples::tie(key, value), theMap) { std::cout << key << " => " << value << "\n"; }
That's neat. Maybe I'll add this as an example to the docs.
Incidentally, if it's not too late I'd like to vote to ACCEPT BOOST_FOREACH into boost.
Officially, the review ended Monday. -- Eric Niebler Boost Consulting www.boost-consulting.com
participants (2)
-
Eric Niebler
-
Joe Gottman