[英]reset boost accumulator c++
在C ++中没有找到重置累加器的“提升”方法,我遇到了一段似乎重置了升压累加器的代码。 但是不知道它是如何实现的。 代码如下-
#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行做什么? “清除”如何设法重置累加器? 另外,有没有我缺少的标准增强方法以及实现上述代码已完成的其他任何方法。
要重新初始化对象,只需执行以下操作:
acc = {};
它的作用是{}
创建一个默认初始化的临时对象,该对象被分配给acc
。
第7到12行做什么?
他们调用对象的析构函数,然后默认在同一存储中构造一个新的(相同类型的)对象。
对于明智的类型,这将与Maxim的答案所建议的效果相同,即为现有对象分配默认构造的临时对象。
第三种选择是使用不同的对象
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
using namespace boost::accumulators;
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;
} // acc's lifetime ends here, afterward it doesn't exist
{
// Define another accumulator set for calculating the mean
accumulator_set<double, stats<tag::mean> > acc;
// Display an empty result
std::cout << "Mean: " << mean(acc) << std::endl;
// push elements again
acc(1.2);
acc(2.3);
acc(3.4);
acc(4.5);
std::cout << "Mean: " << mean(acc) << std::endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.