std::mapをBoost.Foreachで回すときにキーと値を簡単に取り出す

gmane.comp.lib.boost.devel - 【Foreach】 Proposal to simplify using Boost.Foreach with maps


こんなことできたんだ!

#include <iostream>
#include <map>
#include <boost/tuple/tuple.hpp>
#include <boost/foreach.hpp>

int main()
{
    std::map<int, int> m;
    m[1] = 3;
    m[2] = 2;
    m[3] = 1;

    int key, value;
    BOOST_FOREACH(boost::tie(key, value), m)
        std::cout << key << ", " << value << std::endl;
}

ignore使えばvalueだけほしいとき便利かも。

#include <iostream>
#include <map>
#include <boost/tuple/tuple.hpp>
#include <boost/foreach.hpp>

int main()
{
    std::map<int, int> m;
    m[1] = 3;
    m[2] = 2;
    m[3] = 1;

    int value;
    BOOST_FOREACH(boost::tie(boost::tuples::ignore, value), m)
        std::cout << value << std::endl;
}


foreachでmapを使いやすくするために、こんなのも今考えられてるみたいですね。

std::map<int, int> my_map;
BOOST_FOREACH_FIELD((int key)(int value), my_map)
    std::cout << key << " : " << value << "\n";
std::map<int, int> my_map;
BOOST_FOREACH_PAIR(int key, int value, my_map)
    std::cout << key << " : " << value << "\n";