使用 boost.accumulators 对将特定属性设置为值的对象进行计数
Using boost.accumulators to count objects that have a certain attribute set to a value
这是一段为我的问题设置上下文的代码(这是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(或与此相关的标准库)是否提供了我可能忽略的东西,即通过属性值计算列表中的项目数?
使用 std::count_if 和合适的谓词。 例如,要查找 C++11 中age
为 Age_ADULT
的Person
对象的数量,
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
);
相关文章:
- 如何在自删除后将对象设置为nullptr
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- std::用派生类对象设置,但用gcc8.1设置基类比较器
- 如何在 gdb 中的所有构造函数上同时为 C++ 对象设置断点?
- 如何将C++ time_t对象设置为纪元?
- 使用PYBIND11,如何为Array_t对象设置基础内存的所有权
- 如何使用基类对象设置派生类变量的值
- C 不能将对象设置为方法的返回对象
- 一旦对象设置为 null,用于声明对象的堆大小的变量就设置为 null?
- 无法在openGL和GLUT中为我想要的确切对象设置动画
- 如何将2D向量中的对象设置为空指针[C ]
- 如何用类别的consumetrized构造函数声明使用类的比较对象设置的STL设置
- 为什么重载运算符不将主对象设置为值集
- 如何在 OpenGL 中为 3D 对象设置原点
- C++是否可以将fstream对象设置为在每次调用<<
- 如何从C#将对象设置为C++
- 哪个更好?如果子对象是类的成员,则为子对象设置父对象
- c++无法为包含静态变量的对象设置NULL指针
- 将数组中的对象设置为新对象
- 在OpenGL中为不同的对象设置单独的材质属性