gpt4 book ai didi

c++ - 使用 boost::accumulators::statistics 查找数组的中位数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:30 27 4
gpt4 key购买 nike

我有一个在 MATLAB 中计算的大型一维数组。我需要找到这个数组的中位数。我想为此目的使用 boost c++ 库,因为它具有使用 P 平方算法计算中位数的实现,该算法对大型数组有效。下面是将 5 个数字一一推送并使用 boost 库找到中位数的代码。我想更改此代码,以便我可以将数组作为参数传递并找到该数组的中位数。数组的大小很大,所以我不能使用“for 循环”来推送累加器集中的每个元素。

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <iostream>

using namespace boost::accumulators;

int main() {
accumulator_set<double, features<tag::mean, tag::median> > acc;

acc(8);
acc(9);
acc(10);
acc(11);
acc(12);
//double arr[3] = {1,2,3};
//acc(arr);
std::cout << mean(acc) << '\n';
std::cout << median(acc) << '\n';
}

我确实找到了一些要求使用 vector 的资源,但我不明白。一个工作示例,其中一个小数组作为参数传递,然后使用 boost c++ 库找到中位数将受到高度赞赏。

最佳答案

简单迭代:

for (auto d : arr)
acc(d);

或者使用算法:

for_each(begin(arr), end(arr), ref(acc));

Note: use std::ref(acc) to avoid passing by value!

演示

Live On Coliru

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <iostream>

using namespace boost::accumulators;

int main() {
accumulator_set<double, features<tag::mean, tag::median> > acc;

double arr[3] = { 1, 2, 3 };

for (auto d : arr)
acc(d);

using namespace std;
for_each(begin(arr), end(arr), ref(acc));

std::cout << mean(acc) << '\n';
std::cout << median(acc) << '\n';
}

附言:

如果你坚持要有函数接口(interface):

Live On Coliru

template <typename Accum, typename Range>
void do_sample(Accum& accum, Range const& range) {
using namespace std;
for_each(begin(range), end(range), std::ref(accum));
}

(也适用于 vector 或任何其他范围)。打印:

2
3

关于c++ - 使用 boost::accumulators::statistics 查找数组的中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241019/

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