无论向量内部是什么,如何取向量的平均值



我正在处理一个家庭作业问题,该问题要求我找到数据类的基本统计信息。我目前正在寻找平均值,但由于给定文件的结构方式,我不确定如何设置它。

以下是我得到的:

/* Copyright 2018 test_stat_tracker.cc */
#include <cstddef>
// using size_t
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
#include "../hw7/stat_tracker.h"
using csce240::StatTracker;

const int kInt_elems[] = {1, 2, 1, 5, 7, 2, 9};
const size_t kInt_elem_count = 7;
const int kInt_elem_mean = 3;  // actually 27/7
const int kInt_elem_median = 2;
const int kInt_elem_mode[] = {1, 2};

/* Calculates the actual mean, prints the expected and actual values, and
*   returns whether they are the same.
*/
template <class T>
bool TestMean(const StatTracker<T>& tracker, const T& expected) {
T actual = tracker.Mean();
cout << "Expected mean: " << expected
<< ", Actual mean: " << actual;
return actual == expected;
}
void TestIntStats() {
vector<int> elems;
elems.assign(kInt_elems, kInt_elems + kInt_elem_count);
StatTracker<int> tracker;
for (auto it = elems.begin(); it != elems.end(); ++it)
tracker.Add(*it);
if (!TestMean(tracker, kInt_elem_mean))
cout << ": FAILEDn";
else
cout << ": PASSEDn";
}

int main(int argc, char* argv[]) {
TestIntStats();
return 0;
} 

现在这就是我在.h和.cc文件中管理的内容:

/* Copyright 2018
*
* stat_tracker.h 
*/    
#ifndef _HW7_STAT_TRACKER_H_  // NOLINT
#define _HW7_STAT_TRACKER_H_  // NOLINT
#include <ostream>
using std::cout;
using std::endl;
#include <vector>
#include <numeric>
using std::accumulate;
namespace csce240 {
template <class T>
class StatTracker  {
public:
const T Mean() const;  // T = T + T and T = T / int must be defined
// T a, b; a += b; DON'T DO THIS
};
}  // namespace csce240
#include "../hw7/stat_tracker.cc"  // comment out
#endif /* _HW7_STAT_TRACKER_H_ */  // NOLINT 

还有我的.cc文件

/* Copyright 2018
*
* stat_tracker.cc 
*/
// #include "stat_tracker.h"  // NOLINT
namespace csce240 {
template<class T>
const T StatTracker<T>::Mean() const {
auto v(elems);
vector<T> v = accumulate(v.begin(), v.end(), 0)/v.size();
return T();
}
}  // namespace csce240
#include "stat_tracker.h"

目前,我正在努力让平均值发挥作用,但我一直收到一个错误,即elems没有声明。我无法在我的.cc中初始化kInt_elems,因为我的教授将使用他自己的不同数字的测试类。

我很失落,需要一点关于如何设置这个功能的指导。

下面是一些计算向量平均值的代码。限制:

  1. 数据类型必须支持添加
  2. 数据类型必须支持划分
  3. 数据类型必须支持零赋值

代码:

template <typename Data>
Data Mean(const std::vector<Data>& v)
{
Data sum = 0;
const size_t length = v.length();
for (size_t i = 0; i < length; ++i)
{
sum += v[i];
}
return sum / length;
}

这使用基元for循环来对向量中的元素求和。

结果取决于如何为数据类型定义除法。例如,浮点将返回与整型不同的结果。

最新更新