2011-05-19 63 views
1

这里的(这是C++)代码的情况下设置为我的问题的一个片段使用boost.accumulators算有一定的属性设置为一个值

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; 

填充的人名单后的对象,我想要获得清单中有多少项目属于特定性别或年龄的记录。我知道我只需遍历列表并手动计数,但我希望在某处可能会有更好的这种算法的优化版本。我读了关于增强计数累加器的内容,但我不确定在这种特殊情况下可以使用它。

是否boost(或标准库)提供了一些我可能忽略的数值来计算列表中项的数量?

回答

7

使用std::count_if和一个合适的谓词。例如,找Person对象与C++ 11的的Age_ADULTage数,

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

对于C++ 03,

std::count_if(
    people.begin(), 
    people.end(), 
    boost::bind(&Person::age, _1) == Age_ADULT 
); 
相关问题