[英]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.