Boost logo

Boost Users :

Subject: Re: [Boost-users] Compilation/syntax error Boost.Lambda [SOLUTIO]
From: Joost Kraaijeveld (J.Kraaijeveld_at_[hidden])
Date: 2010-02-07 14:43:03


Thanks to Steven and my own thinking a solution:

#include <iostream>
#include <map>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/algorithm.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/if.hpp>
#include <boost/function.hpp>
#include <functional>

template< typename Key, typename Value, typename Predicate >
std::map< Key, Value > copy_if( const std::map< Key, Value >& aMap, const Predicate& aPredicate)
{
        using namespace std;
        using namespace boost::lambda;

        pair< typename map< Key, Value >::iterator, bool > (map< Key, Value >::*InsertFn)(const typename map< Key, Value >::value_type&) = &map< Key, Value >::insert;
        map<Key, Value > matchedObjects;
        for_each( aMap.begin(),
                    aMap.end(),
                    if_then(
                            bind( aPredicate, _1),
                              bind( InsertFn,
                                          &matchedObjects ,
                                          bind( &make_pair< typename std::map < Key, Value >::key_type,typename map< Key, Value >::mapped_type >,
                                                       bind(&map< Key, Value >::value_type::first, _1),
                                                       bind(&map< Key, Value >::value_type::second,_1)))));
        return matchedObjects;
}

int main( int argc,
                        char* argv[])
{
        std::map<std::string, std::string> objectsMap;
        objectsMap.insert(std::make_pair("one","value1"));
        objectsMap.insert(std::make_pair("two","value2"));
        objectsMap.insert(std::make_pair("three","value3"));

        boost::function< bool (std::map<std::string, std::string>::value_type)> mapPredicate = boost::lambda::bind(&std::map<std::string, std::string>::value_type::second,boost::lambda::_1) == "value3";
        std::map<std::string, std::string> matchedObjectsMap = copy_if(objectsMap,mapPredicate);
        std::for_each( matchedObjectsMap.begin(),
                              matchedObjectsMap.end(),
                              std::cout << boost::lambda::bind(&std::map<std::string, std::string>::value_type::first, boost::lambda::_1) << boost::lambda::constant(" ") << boost::lambda::bind(&std::map<std::string, std::string>::value_type::second, boost::lambda::_1) << '\n');
        return 0;
}

-- 
Groeten,
Joost Kraaijeveld
Askesis B.V.
Molukkenstraat 14
6524NB Nijmegen
tel: 024-3888063 / 06-51855277
fax: 024-3608416
web: www.askesis.nl

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net