Re: peek inside container's elements from UnaryPredicate
In article <y1rvdzkb07z.fsf@ics.uci.edu>,
Rares Vernica <rares@ics.uci.edu> wrote:
Hello,
Suppose I have a container of pair<int, int>, how would I use the
predefined function objects/adapters (e.g., greater, bind1st, mem_func,
compose_f_gx) and the "count" function from <algorithm> to get and
number of pairs, "p", that have "p.first > 5"?
Writing a custom UnaryPredicate function is easy, but I would
prefer to use the predefined ones if possible.
The standard doesn't have compose_f_gx/compose1 or select1st.
Example:
std::list<std::pair<int, int> > c;
// insert elements in c
int x = count(c.begin(), c.end(), /* UnaryPredicate */);
// x is the number of pairs, p, with p.first > 5
You have to use count_if, not count.
int x = count_if(c.begin(), c.end(),
compose1(bind2nd(greater<int>(), 5), select1st<pair<int,int> >()));
More general, how can I compose the predefined function
objects/adapters, so that the resulting UnaryPredicate peeks inside the
elements of a container?
template < typename Pair >
struct select1st :
public std::unary_function< Pair, typename Pair::first_type >
{
const typename Pair::first_type& operator()( const Pair& x ) const {
return x.first;
}
typename Pair::first_type& operator()( Pair& x ) const {
return x.first;
}
};