使用rxcpp对聚合函数进行分组
Groups aggregate functions using rxcpp?
我正试图了解RxCpp的要点,这是微软反应式扩展的原生cpp实现,看看我是否可以在项目中使用它,但我很难理解这些概念。
如果我有一个具有以下结构的可观察模板:
struct Person
{
std::string name;
std::string sex;
int age;
}
我该如何创建另一个可观察的数据,按性别分组,包括所有事件的人数、最小年龄、最大年龄和平均年龄?
我看过一些例子,但我不知道如何一次获得多个聚合。
使用group_by按性别进行划分,然后组合最小/最大/平均递减器,以产生每个性别所需的输出。
更新计数、输出和附加评论
这对我有效:
#include "rxcpp/rx.hpp"
using namespace rxcpp;
using namespace rxcpp::sources;
using namespace rxcpp::subjects;
using namespace rxcpp::util;
using namespace std;
struct Person
{
string name;
string gender;
int age;
};
int main()
{
subject<Person> person$;
// group ages by gender
auto agebygender$ = person$.
get_observable().
group_by(
[](Person& p) { return p.gender;},
[](Person& p) { return p.age;});
// combine min max and average reductions.
auto result$ = agebygender$.
map([](grouped_observable<string, int> gp$){
// the function passed to combine_latest
// will be called once all the source streams
// (count, min, max, average) have produced a
// value. in this case, all the streams are reducers
// that produce only one value when gp$ completes.
// thus the function is only called once per gender
// with the final value of each stat.
return gp$.
count().
combine_latest(
[=](int count, int min, int max, double average){
return make_tuple(gp$.get_key(), count, min, max, average);
},
gp$.min(),
gp$.max(),
gp$.map([](int age) -> double { return age;}).average());
}).
// this map() returns observable<observable<tuple<string, int, int, int, double>>>
// the merge() returns observable<tuple<string, int, int, int, double>>
// a grouped observable is 'hot' if it is not subscribed to immiediatly (in this case by merge)
// then the values sent to it are lost.
merge();
// display results
result$.
subscribe(apply_to([](string gender, int count, int min, int max, double avg){
cout << gender << ": count = " << count << ", range = [" << min << "-" << max << "], avg = " << avg << endl;
}));
//provide input data
observable<>::from(
Person{"Tom", "Male", 32},
Person{"Tim", "Male", 12},
Person{"Stel", "Other", 42},
Person{"Flor", "Female", 24},
Person{"Fran", "Female", 97}).
subscribe(person$.get_subscriber());
return 0;
}
结果输出
Female: count = 2, range = [24-97], avg = 60.5
Male: count = 2, range = [12-32], avg = 22
Other: count = 1, range = [42-42], avg = 42
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 使用rxcpp对聚合函数进行分组
- rxcpp - 为什么当可观察量发出值时,不调用所有观察者的on_next函数