Connecting Tech Pros Worldwide Forums | Help | Site Map

peek inside container's elements from UnaryPredicate

Rares Vernica
Guest
 
Posts: n/a
#1: Jul 5 '08
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 <algorithmto 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.

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

More general, how can I compose the predefined function
objects/adapters, so that the resulting UnaryPredicate peeks inside the
elements of a container?

Thanks,
Rares

Daniel T.
Guest
 
Posts: n/a
#2: Jul 5 '08

re: peek inside container's elements from UnaryPredicate


In article <y1rvdzkb07z.fsf@ics.uci.edu>,
Rares Vernica <rares@ics.uci.eduwrote:
Quote:
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 <algorithmto 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.
Quote:
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()));
Quote:
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;
}
};
Closed Thread