在 C++ 中,如何使用向量视图和 gsl_stats_mean 计算整数向量的平均值? [英] In C++, how to compute the mean of a vector of integers using a vector view and gsl_stats_mean?

查看:29
本文介绍了在 C++ 中,如何使用向量视图和 gsl_stats_mean 计算整数向量的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序处理整数的STL向量,但有时我需要计算一些关于它们的统计数据.因此我使用GSL 函数.为了避免将 STL 向量复制到 GSL 向量中,我创建了一个 GSL 向量视图,并将其提供给 GSL 函数,如以下代码所示:

my program manipulates STL vectors of integers but, from time to time, I need to calculate a few statistics on them. Therefore I use the GSL functions. To avoid copying the STL vector into a GSL vector, I create a GSL vector view, and give it to the GSL functions, as in this piece of code:

#include <iostream>
#include <vector>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_statistics.h>
using namespace std;

int main( int argc, char* argv[] )
{
  vector<int> stl_v;
  for( int i=0; i<5; ++i )
    stl_v.push_back( i );

  gsl_vector_int_const_view gsl_v = gsl_vector_int_const_view_array( &stl_v[0], stl_v.size() );

  for( int i=0; i<stl_v.size(); ++i )
    cout << "gsl_v_" << i << "=" << gsl_vector_int_get( &gsl_v.vector, i ) << endl;

  cout << "mean=" << gsl_stats_mean( (double*) gsl_v.vector.data, 1, stl_v.size() ) << endl;
}

一旦编译(gcc -lstdc++ -lgsl -lgslcblas test.cpp),这段代码输出:

Once compiled (gcc -lstdc++ -lgsl -lgslcblas test.cpp), this code outputs this:

gsl_v_0=0
gsl_v_1=1
gsl_v_2=2
gsl_v_3=3
gsl_v_4=4
mean=5.73266e-310

矢量视图已正确创建,但我不明白为什么平均值是错误的(它应该等于 10/5=2).任何的想法?提前致谢.

The vector view is properly created but I don't understand why the mean is wrong (it should be equal to 10/5=2). Any idea? Thanks in advance.

推荐答案

使用整数统计函数:

cout << "mean=" << gsl_stats_int_mean( gsl_v.vector.data, 1, stl_v.size() ) << endl;

注意 gsl_stats_int_mean 而不是 gsl_stats_mean.

这篇关于在 C++ 中,如何使用向量视图和 gsl_stats_mean 计算整数向量的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆