开发者

Using boost.accumulators to count objects that have a certain attribute set to a value

Here's a snippet of code setting the context to my question (this is C++)

enum Gender { Gender_MALE, Gender_FEMALE, Gender_UNKNOWN };
enum Age { Age_CHILD, Age_ADULT, Age_SENIOR, Age_UNKNOWN };

struct Person {
  int id;
  Gender gender;
  Age age;
};

std::list<Person> people;

After populating the list of people, I would like to obtain a tally of how many items in the list are of a particular gender or age. I know I can simply iterate through the list and count manually, but I was hoping there might be a better optimized version of such an algorithm somewhere. I read about t开发者_Python百科he boost count accumulator, but I'm not sure I can use that in this particular situation.

Does boost (or the standard library for that matter) offer something I might have overlooked to count the number of items in a list by the value of an attribute?


Use std::count_if and a suitable predicate. E.g., to find the number of Person objects with an age of Age_ADULT in C++11,

std::count_if(
    people.cbegin(),
    people.cend(),
    [](Person const& p){ return p.age == Age_ADULT; }
);

For C++03,

std::count_if(
    people.begin(),
    people.end(),
    boost::bind(&Person::age, _1) == Age_ADULT
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜