Loïc
Loïc

Reputation: 13

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

I'm trying to create a function that calculates the average of all the numbers in my array. But when I run the code the vector in my header says its undeclared. What should I change ?

I have tried putting #include in my header file and using namespace std; but it still doesn't fix my problem. I have also tried passing my function as reference.

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

Upvotes: 0

Views: 1194

Answers (2)

R Sahu
R Sahu

Reputation: 206747

  1. Add #include <vector>.
  2. Use std::vector instead of just vector.
  3. While at it, change the argument type to const&.

#ifndef MATH_H_INCLUDED
#define MATH_H_INCLUDED

#include <vector>

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

#endif  MATH_H_INCLUDED

Upvotes: 4

Elro444
Elro444

Reputation: 136

You need to add #include <vector> in math.h instead of in math.cpp

Upvotes: 0

Related Questions