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

StackOverflow https://stackoverflow.com/questions/6062432

  •  15-11-2019
  •  | 
  •  

Pregunta

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 the 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?

¿Fue útil?

Solución

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
);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top