Created
October 9, 2012 17:53
-
-
Save farseerfc/3860321 to your computer and use it in GitHub Desktop.
try to implement a count_if using boost accumulator framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <functional> | |
#include <boost/mpl/placeholders.hpp> | |
#include <boost/accumulators/accumulators.hpp> | |
#include <boost/accumulators/statistics/count.hpp> | |
#include <boost/foreach.hpp> | |
#include <boost/parameter/keyword.hpp> | |
#define array_size(p) (sizeof(p)/sizeof(*p)) | |
#define array_end(p) (p+array_size(p)) | |
namespace boost { namespace accumulators { | |
BOOST_PARAMETER_NESTED_KEYWORD(tag, count_if_value, if_value) | |
namespace impl{ | |
template<typename Sample,typename Tag > | |
struct count_if_impl : accumulator_base{ | |
typedef std::size_t result_type; | |
template<typename Args> | |
count_if_impl(Args const & args): | |
cnt(0), | |
if_value(args[count_if_value]) | |
{} | |
template<typename Args> | |
void operator()(Args const &args){ | |
if((args[parameter::keyword<Tag>::get()])< if_value){ | |
++cnt; | |
} | |
} | |
result_type result(dont_care) const{ | |
return cnt; | |
} | |
private: | |
result_type cnt; | |
int if_value; | |
}; | |
} | |
namespace tag{ | |
struct count_if:depends_on<>,count_if_value { | |
typedef std::size_t result_type; | |
typedef accumulators::impl::count_if_impl<mpl::_1, tag::sample> impl; | |
}; | |
} | |
}} | |
using namespace boost::accumulators; | |
int main(){ | |
int data[] = {8,2,5,1,5,7,2,5,2,6,8,2,2,4,7,1}; | |
accumulator_set< int, features< tag::count_if > > acc(tag::count_if::if_value=4); | |
BOOST_FOREACH( int d ,data ){ | |
acc(d); | |
} | |
std::cout<<extract_result<tag::count_if >(acc)<<std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment