How to create a vector of class objects in C++?

c++, reference, vector

Solution

vector<Site> myStack();

This is actually a function declaration. The function is called `myStack` and it returns a `vector<Site>`. What you actually want is:

vector<Site> myStack;

The type of `neighbours` at the moment will store copies of the objects, not references. If you really want to store references, I recommend using a `std::reference_wrapper` (rather than using pointers):

vector<reference_wrapper<Site>> neighbors;

Problem

I am trying to create a simple stack using vector in C++. Here is the code: ``` #include <vector> class Site { public: int i; // site position i (x-axis) int s; // site state vector<Site> neighbors; Site(void); Site(int ii, int ss); void AddNeighbor(Site &site); }; Site::Site() { i = -1; s = -1; vector<Site> neighbors; } Site::Site(int ii, int ss) { i = ii; s = ss; } void Site::AddNeighbor(Site &site) { neighbors.push_back(site); } void testStack() { int tot = 600; vector<Site> myStack(); int i = 0; while (i < tot) { Site site(i, 1); myStack.push_back(site); i++; } i = 0; while (i < tot) { Site *site = myStack.back(); myStack.pop_back(); cout << site->i << site->s << endl; i++; } } ``` Compiler errors: ising_wolff.cpp: In function ‘void testStack()’: ising_wolff.cpp:373:17: error: request for member ‘push_back’ in ‘myStack’, which is of non-class type ‘std::vector()’ myStack.push_back(site); ^ ising_wolff.cpp:380:30: error: request for member ‘back’ in ‘myStack’, which is of non-class type ‘std::vector()’ Site *site = myStack.back(); ^ ising_wolff.cpp:381:17: error: request for member ‘pop_back’ in ‘myStack’, which is of non-class type ‘std::vector()’ myStack.pop_back(); What do these errors mean? Here are some sites I have looked at: 1) Creating objects while adding them into vectors 2) push_back causing errors in C 3) how to create vectors of class object

Original source

Related problems