C++初学者真诚求高手指点,万谢万谢!
请看一下程序:#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<vector>
#include<cmath>
using namespace std;
class MVector
{
// storage for the new vector class
std::vector<double> v;
public:
// constructor
explicit MVector(){};
explicit MVector(int n):v(n){};
explicit MVector(int n,double x):v(n,x){};
// destructor
~MVector(){};
// equate vectors;
MVector& operator=(const MVector& X)
{if(&X==this)return *this;v=X.v;return *this;};
// access data in vector
double& operator[](int index){return v[index];};
// access data in vector (const)
double operator[](int index) const {return v[index];};
// size of vector
int size() const {return v.size();};
void push_back(double x){v.push_back(x);}
}; // end class MVector
void runningaverage(const MVector &v,int m,int p)
{
MVector runningaverage(v.size()-m-p);
cout << " runningaverage:= ( ";
for(int i=0;i<=runningaverage.size();i++)
{
double sum=0.;
for(int j=i;j<=i+m+p;j++){sum+=v[j];}
runningaverage[i]=sum/(m+p+1);
cout << runningaverage[i] << " " ;
}
cout << ")\n";
}
int main(int argc, char** argv)
{
MVector x;
x.push_back(1.2);
x.push_back(2.1);
x.push_back(1.9);
x.push_back(3.4);
x.push_back(3.9);
x.push_back(2.7);
x.push_back(1.6);
x.push_back(2.3);
x.push_back(2.4);
cout << " x:= ( ";
for (int i=0;i<x.size();i++)
cout << x[i] << " ";
cout << ")\n";
runningaverage(x,2,1);
}
先说下我想求一个数列的移动平均数runningaverage,其定义见附件的图。
之前都是好好,Class MVector的部分是照搬老师的,完全没有问题,问题出现在加了runningaverage函数以后,所以你仔细看看runningaverage的循环。结果是能运行出来的,就是跳出俩窗口说
1、Expression:vector subscript out of range.
2、Expression:("Standard C++ libraries out of range",0)
为什么会这样呢?不明白。求解答。
万谢万谢!!