c++ - 重置 boost 累加器 C++

标签 c++ boost boost-accumulators

由于没有找到在 C++ 中重置累加器的“boost ”方法,我遇到了一段似乎可以重置 boost 累加器的代码。但是不明白它是如何实现的。代码如下-

#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
using namespace boost::accumulators;

template< typename DEFAULT_INITIALIZABLE >
inline void clear( DEFAULT_INITIALIZABLE& object )
{
        object.DEFAULT_INITIALIZABLE::~DEFAULT_INITIALIZABLE() ;
        ::new ( boost::addressof(object) ) DEFAULT_INITIALIZABLE() ;
}

int main()
{
    // Define an accumulator set for calculating the mean 
    accumulator_set<double, stats<tag::mean> > acc;

    float tmp = 1.2;
    // push in some data ...
    acc(tmp);
    acc(2.3);
    acc(3.4);
    acc(4.5);

    // Display the results ...
    std::cout << "Mean:   " << mean(acc) << std::endl;
    // clear the accumulator
    clear(acc);
    std::cout << "Mean:   " << mean(acc) << std::endl;
    // push new elements again
    acc(1.2);
    acc(2.3);
    acc(3.4);
    acc(4.5);
    std::cout << "Mean:   " << mean(acc) << std::endl;

    return 0;
}

第 7 行到第 12 行是做什么的? “清除”如何设法重置累加器? 另外,是否有我缺少的标准 boost 方式以及实现上述代码所做的任何其他方式。

最佳答案

要重新初始化对象,只需执行以下操作:

acc = {};

它的作用是{} 创建一个默认初始化的临时对象,该对象被分配给 acc

关于c++ - 重置 boost 累加器 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54572646/

相关文章:

c++ - C++中两个/两个以上对象的重载加法赋值运算符?

c++ - 如何将 NS 基本数组传递给静态 C++ dll

c++ - 堆上没有匹配函数

c++ - Boost Geometry/intersection() 似乎返回不一致的结果

c++ - open ofstream 作为类属性

c++ - Armadillo的cx_mat和Boost的odeint编译报错

c++ - boost::thread 变量的前向声明

c++ - boost 累加器滚动计数非零

c++ - 如何初始化 boost 滚动窗口累加器?