gpt4 book ai didi

c++ - 是否可以将 boost 累加器与 vector 一起使用?

转载 作者:IT老高 更新时间:2023-10-28 23:01:37 27 4
gpt4 key购买 nike

我想使用 boost 累加器来计算一个 vector 变量的统计数据。有没有一种简单的方法可以做到这一点。我认为不可能使用最愚蠢的东西:

  using namespace boost::accumulators;
//stuff...

accumulator_set<vector<double>, stats<tag::mean> > acc;
vector<double> some_vetor;
//stuff
some_vector = doStuff();
acc(some_vector);

也许这很明显,但我还是尝试了。 :P

我想要的是有一个累加器来计算一个 vector ,该 vector 是许多 vector 分量的平均值。有没有简单的出路?

编辑:

我不知道我是否完全清楚。我不想要这个:

 for_each(vec.begin(), vec.end(),acc); 

这将计算给定 vector 的条目的平均值。我需要的是不同的。我有一个会吐出 vector 的函数:

 vector<double> doSomething(); 
// this is a monte carlo simulation;

我需要运行多次并计算这些 vector 的 vector 平均值:

  for(int i = 0; i < numberOfMCSteps; i++){
vec = doSomething();
acc(vec);
}
cout << mean(acc);

我希望 mean(acc) 本身是一个 vector ,其条目 [i] 将是累积 vector 的条目 [i] 的均值。

Boost 的文档中有关于此的提示,但没有明确说明。而且我有点笨。 :P

最佳答案

我对您的问题进行了一些调查,在我看来 Boost.Accumulators 已经为 std::vector 提供了支持。 .这是我可以在 a section of the user's guide 中找到的内容:

Another example where the Numeric Operators Sub-Library is useful is when a type does not define the operator overloads required to use it for some statistical calculations. For instance, std::vector<> does not overload any arithmetic operators, yet it may be useful to use std::vector<> as a sample or variate type. The Numeric Operators Sub-Library defines the necessary operator overloads in the boost::numeric::operators namespace, which is brought into scope by the Accumulators Framework with a using directive.

确实,经过验证,文件boost/accumulators/numeric/functional/vector.hpp 确实包含使“幼稚”解决方案发挥作用所必需的运算符。

我相信你应该试试:

  • 包括
    • boost/accumulators/numeric/functional/vector.hpp在任何其他累加器标题之前
    • boost/accumulators/numeric/functional.hpp在定义 BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT
  • 使用 using namespace boost::numeric::operators; 将运算符纳入范围.

只剩下最后一个细节:执行将在运行时中断,因为初始累积值是默认构造的,并且在尝试将大小为 n 的 vector 添加到空 vector 时会发生断言.为此,您似乎应该使用(其中 n 是 vector 中的元素数)初始化累加器:

accumulator_set<std::vector<double>, stats<tag::mean> > acc(std::vector<double>(n));

我尝试了以下代码,mean给我一个std::vector大小 2:

int main()
{
accumulator_set<std::vector<double>, stats<tag::mean> > acc(std::vector<double>(2));

const std::vector<double> v1 = boost::assign::list_of(1.)(2.);
const std::vector<double> v2 = boost::assign::list_of(2.)(3.);
const std::vector<double> v3 = boost::assign::list_of(3.)(4.);
acc(v1);
acc(v2);
acc(v3);

const std::vector<double> &meanVector = mean(acc);
}

我相信这就是你想要的?

关于c++ - 是否可以将 boost 累加器与 vector 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4316716/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com