【问题标题】:How to initialize a boost rolling window accumulator?如何初始化升压滚动窗口累加器?
【发布时间】:2020-10-16 07:21:33
【问题描述】:

我想初始化一个 boost 滚动窗口累加器,而不必在函数调用中进行赋值。

我看到每个人都这样做:

boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::rolling_mean>> acc(boost::accumulators::tag::rolling_window::window_size = 10);

如果没有在上面的构造函数调用中进行赋值,我如何制作相同的累加器?

【问题讨论】:

  • 您之前是否尝试过创建变量并使用它?当你这样做时会发生什么?

标签: c++ boost boost-accumulators


【解决方案1】:

这不是作业,而是a named-argument idiom。 C++ 没有这个,真的,所以这就是为什么它看起来像一个赋值:它是一个Expression Template

您当然可以找出类型并使用它,但这不会有任何区别,只会使正确使用库变得更加困难:

boost::parameter::aux::tagged_argument_list_of_1<
    boost::parameter::aux::tagged_argument<
        boost::accumulators::tag::rolling_window_size_<0>, const int>>
    init(10);

ba::accumulator_set<double, ba::stats<ba::tag::rolling_mean>> acc(init);

我不了解你,但我更喜欢命名参数表达式。


您显然可以编写一个辅助函数来删除库详细信息:

auto make_accum(int window) {
    return ba::accumulator_set<
        double,
        ba::stats<ba::tag::rolling_mean>> (ba::tag::rolling_window::window_size = window);
}

int main() {
    auto acc = make_accum(10);
}

这只是使用关于您集合中的统计信息的知识将命名参数转换为位置参数。

如果您担心泛型代码,只需在泛型情况下将表达式作为初始值设定项传递即可。这就是库 istelf 的实现方式:

template <typename Stats, typename... Init> auto generic_accum(Init const&... init) {
    return ba::accumulator_set<double, Stats> (init...);
}

演示所有 3 种方法

Live On Coliru

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>

namespace ba = boost::accumulators;

template <typename Stats, typename... Init> auto generic_accum(Init const&... init) {
    return ba::accumulator_set<double, Stats> (init...);
}

auto make_accum(int window) {
    return ba::accumulator_set<
        double,
        ba::stats<ba::tag::rolling_mean>> (ba::tag::rolling_window::window_size = window);
}

int main() {
    {
        boost::parameter::aux::tagged_argument_list_of_1<
            boost::parameter::aux::tagged_argument<
            boost::accumulators::tag::rolling_window_size_<0>, const int>>
            init(10);

        ba::accumulator_set<double, ba::stats<ba::tag::rolling_mean>>
            acc(init);
    }

    {
        auto acc = make_accum(10);
    }

    {
        auto acc = generic_accum<ba::stats<ba::tag::rolling_mean>>(ba::tag::rolling_window::window_size = 10);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2019-07-01
    • 2022-01-09
    相关资源
    最近更新 更多