使用 boost.accumulators 对将某个属性设置为某个值的对象进行计数

发布于 2024-11-08 16:04:41 字数 449 浏览 6 评论 0原文

这是设置我的问题上下文的代码片段(这是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美人骨 2024-11-15 16:04:41

使用 std::count_if 和合适的谓词。例如,要在 C++11 中查找 ageAge_ADULTPerson 对象的数量,

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
);

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
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文