使用 boost.accumulators 对将某个属性设置为某个值的对象进行计数
这是设置我的问题上下文的代码片段(这是 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;
在填充人员列表后,我想获得列表中具有特定性别或年龄的项目的计数。我知道我可以简单地迭代列表并手动计数,但我希望在某个地方可能有这种算法的更好的优化版本。我读过有关升压计数累加器的信息,但我不确定是否可以在这种特殊情况下使用它。
boost(或与此相关的标准库)是否提供了我可能忽略的功能,可以通过属性的值来计算列表中的项目数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 std::count_if 和合适的谓词。例如,要在 C++11 中查找
age
为Age_ADULT
的Person
对象的数量,对于 C++03,
Use std::count_if and a suitable predicate. E.g., to find the number of
Person
objects with anage
ofAge_ADULT
in C++11,For C++03,