0

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 
2
  • 2
    You don't #include <vector> in math.h. Also prefer to explicitely state scope with std:: rather than using namespace std; Commented Apr 15, 2019 at 18:45
  • 3
    math.h is a C standard header. You should avoid using that file name for your header. Commented Apr 15, 2019 at 18:47

2 Answers 2

4
  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 
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

I have already tried that and it still gives me the same errors
That is because in math.h, you did not specify the namespace, so either write std::vector or add using namespace std; in the header itself
Thanks I tried both #include <vector> and using namespace std; on their own instead of putting both at the same time dumb mistake.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.