Skip to content

Instantly share code, notes, and snippets.

@farseerfc
Created October 9, 2012 17:53
Show Gist options
  • Save farseerfc/3860321 to your computer and use it in GitHub Desktop.
Save farseerfc/3860321 to your computer and use it in GitHub Desktop.
try to implement a count_if using boost accumulator framework
#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