mapの検索と値取得

gmane.comp.lib.boost.devel - BOOST_FOREACH like macro for map


mapの検索と値の取得を行うのにいまこんなコードを書いてるけど

map<string, string>::const_iterator it = aStringMap.find("key")
if (it != aStringMap.end()) {
    process(it->second)
}

Boost.Foreachみたいにこんな感じで書きたい、というお話。

BOOST_CONSTMAPFIND(aStringMap, "key", data)
{
    process(data);
}


MLでは、見つからなかったときに例外を投げるような関数が解決案として提示されてるみたいですが
私としては、boost::optionalを使ってこんな感じにしたほうがいいと思うんだけど、どうだろう。

#include <iostream>
#include <map>
#include <string>
#include <boost/optional.hpp>

template <class Map, class Key>
boost::optional<typename Map::mapped_type>
    map_find(const Map& m, const Key& key)
{
    typename Map::const_iterator it = m.find(key);
    return it != m.end() ? it->second : boost::optional<typename Map::mapped_type>();
}

int main()
{
    std::map<std::string, int> m;

    m["Akira"]  = 24;
    m["Millia"] = 16;
    m["Johnny"] = 38;

    if (boost::optional<int> value = map_find(m, "Akira"))
        std::cout << value.get() << std::endl;
    else
        std::cout << "Not Found" << std::endl;
}

例外版とoptional版の両方を用意して、成功と失敗のどちらが確率高いかで使い分けるのもアリかな。
(例外:成功時のコストが低く、失敗時のコストが高い。optional:成功時のコストが高く、失敗時のコストが低い)