Gabriel Shen
Gabriel Shen

Reputation: 99

C++ 'vector' was not declared in this scope

I'm getting an error everytime I compile the function.cpp file saying that stocks and newStock are not declared in this scope. I'm trying to use a struct inside a vector. Thanks for the help.

This is the main.cpp file

#include <fstream>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;

struct Stocks
{
    int one;
    int two;
    int three;
};

vector<Stocks> portfolio;

#include "testProject2.h"

int main()
{
buyStock(portfolio);

} 

This is the header file.

#include <iostream>

void buyStock(vector<Stocks>& Portfolios);

This is the function.cpp file

#include <iostream>
#include <vector>
#include "testProject2.h"

void buyStock(vector<Stocks>& Portfolios)
{
Stocks newStock;
newStock{1,2,3};
Portfolios.push_back(newStock);
}

Upvotes: 2

Views: 10256

Answers (2)

FBergo
FBergo

Reputation: 1070

Your function.cpp file has no way to know what the Stocks struct is. Define it in the header file:

struct Stocks {
   int one;
   int two;
   int three;
};

And remove its definition from main.cpp.

Also in your header file, you need

#include <vector>

and refer to vector parameter as std::vector<Stocks> &Portfolios (better than using namespace std;)

Your initialization syntax newstock{1,2,3} looks incorrect too.

Upvotes: 4

Kostas
Kostas

Reputation: 4186

You use vector in your header file without it being defined.

Try changing the header file to this:

#include <vector>
#include <Stocks.h> // name of .h file where Stocks is defined

void buyStock(std::vector<Stocks>& Portfolios);

// OR

using namespace std::vector;
void buyStock(vector<Stocks>& Portfolios);

Upvotes: 2

Related Questions