如何获取boost::accumulator_set中最后添加的值?
获取boost::accumulator_set的最后一个输入值
Boost Accumulators库确实支持获取最后一个传入累加器的值,你可以直接使用boost::accumulators::tag::last标签,搭配对应的提取器boost::accumulators::last来实现,用法和你预想的last(my_acc)完全一致。
具体步骤如下:
- 在定义
accumulator_set时,将tag::last加入到features列表中,和你已经在使用的tag::min、tag::max、tag::mean放在一起。 - 当需要获取最后一个输入值时,直接调用
last(你的累加器对象)即可。
示例代码:
#include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> using namespace boost::accumulators; int main() { // 定义包含min、max、mean、last的累加器 accumulator_set<double, features<tag::min, tag::max, tag::mean, tag::last>> acc; acc(1.5); acc(2.7); acc(3.2); // 提取各统计值 double last_val = last(acc); // 结果为3.2 double min_val = min(acc); // 结果为1.5 double max_val = max(acc); // 结果为3.2 double avg_val = mean(acc); // 结果为(1.5+2.7+3.2)/3 ≈ 2.4667 return 0; }
这个tag::last是库原生支持的统计标签,不需要额外自定义实现,和你熟悉的其他统计标签用法完全统一。
内容的提问来源于stack exchange,提问作者JoL
相关产品推荐
相关产品推荐

