mu***********@h otmail.com (JohanS) wrote:
count(v.begin() , v.end(), 5) is easy for a vector of int's.
But how do i make it work with a class object? I have tried a few ways
but can't get it to work since i don't really understand how this
stuff works yet.
If i have class A with 2 int members that you get with A.x() and A.y()
and i want to use count or count_if if A.y() == value.
I have found out how to call member functions with for_each(v.begi n(),
v.end(), mem_fun_ref(&A: :y)). But this still doesn't solve my problem.
Help please
If you want to count how many objects have y() == 5 then you can do
something like this:
count_if( v.begin(), v.end(),
compose1( bind2nd( equal_to<int>() , 5 ), mem_fun_ref( &A::y ) ) );
Where compose1 (which is a part of the STL but didn't make it into
standard C++) is implemented like this:
template < typename Op1, typename Op2>
class unary_compose : public std::unary_func tion<
typename Op2::argument_t ype, typename Op1::result_typ e >
{
Op1 fn1;
Op2 fn2;
public:
unary_compose( const Op1& x, const Op2& y ) : fn1( x ), fn2( y ) { }
typename Op1::result_typ e operator( )(
const typename Op2::argument_t ype& x ) const
{
return fn1( fn2( x ) );
}
};
template < typename Op1, typename Op2 >
inline unary_compose< Op1, Op2 > compose1( const Op1& fn1,
const Op2& fn2 )
{
return unary_compose< Op1, Op2 >( fn1, fn2 );
}