Re: Using boost::lambda with std::count_if
francis_r <francis.rammeloo@gmail.com> writes:
I have following class:
class User
{
public:
enum Status
{
Online,
Away
Offline
};
User(const std::string & name, Status status);
Status status() const;
const std::string & name() const;
private:
std::string mName;
Status mStatus;
};
And I have a vector:
std::vector<User> users;
Now I want to use count_if to count all users that have not the
Offline status. I can do this by writing a predicate function of
course but I think it would be nice to do this using a lambda
expression.
I can't figure out how to write the expression. Idealy it would look
something like this I think:
count_if(users.begin(), users.end(), lambda::_1.status() !=
User::Offline);
But that doesn't compile, as I expected.
Indeed. The type of _1 doesn't have a member function named status.
std::count_if(users.begin(), users.end(),
boost::bind(&User::status,_1)!=User::Offline);
works for me.
Another question: suppose I do write following predicate functions:
bool Predicate_UserOnline(const User& user)
{ return user.status() == User::Online; }
bool Predicate_UserAway(const User& user)
{ return user.status() == User::Away;}
bool Predicate_UserOffline(const User& user)
{ return user.status() == User::Offline; }
Is it then possible to count the users, using count_if, that are
either Online or Away? It would be !Predicate_UserOffline, but I can't
use that expression as a function pointer.
But you can use
!boost::bind(&Predicate_UserOffline,_1)
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]