如何在我的 header 文件中修复('vector':未声明的标识符)?

How to fix ( 'vector' : undeclared identifier ) in my header file?

我正在尝试创建一个函数来计算数组中所有数字的平均值。但是当我 运行 代码时,我 header 中的向量表示它未声明。我应该改变什么?

我试过将#include 放入我的 header 文件并使用 namespace std;但它仍然不能解决我的问题。我也试过将我的函数作为参考传递。

Source.cpp

#include <iostream>
#include <string>
#include "math.h"
#include <vector>

using namespace std;


int main()
{


    vector<int> notes;
    notes.push_back(8);
    notes.push_back(4);
    notes.push_back(3);
    notes.push_back(2);

     cout << average(notes) << '\n';

}

math.cpp

#include "math.h"
#include <vector>

using namespace std;



int average(vector<int>  tableau)
{  
    int moyenne(0);
    for (int i(0); i < tableau.size(); i++)
    {
        moyenne += tableau[i];

    }

    return moyenne / tableau.size();
}

math.h

#ifndef MATH_H_INCLUDED
#define MATH_H_INCLUDED

int average(vector<int>  tableau);

#endif  MATH_H_INCLUDED

您需要在 math.h 中添加 #include <vector> 而不是 math.cpp

  1. 添加#include <vector>.
  2. 使用 std::vector 而不是 vector.
  3. 同时,将参数类型更改为 const&

#ifndef MATH_H_INCLUDED
#define MATH_H_INCLUDED

#include <vector>

int average(std::vector<int> const& tableau);

#endif  MATH_H_INCLUDED