Trying to create a vector of objects

Go To StackoverFlow.com

0

I'm trying to create a vector of objects, i don't know what is going wrong.

here the code

class nave {
public:
    void sx(int i); int x();
    void sy(int i); int y();
};
vector<nave> naves();
naves.push_back(nave);
cout << naves.size();
2012-04-04 19:53
by Mete
FYI, this is know as the most vexing parse - André Caron 2012-04-04 19:56
thank you for the informatio - Mete 2012-04-04 20:03
You should always include the errors that you get. Just saying "I don't know what is going wrong" without posting any kind or error message, or indicating whether error is compile-time or run-time, could prevent you from receiving helpful answers. This code is simple enough for this not to matter, but do it anyway as a matter of policy - Branko Dimitrijevic 2012-04-04 20:23


4

Change -

vector<nave> naves(); // naves() is a function declaration whose return type
                      // is vector<nave>

to

vector<nave> naves;
2012-04-04 19:54
by Mahesh


4

A vector is just like any other class. Declare it thus:

vector<nave> naves;
2012-04-04 19:54
by MPelletier
g++ keep returning "expected primary-expression before ')' token" in the "naves.push_back(nave);" lin - Mete 2012-04-04 19:59
You cannot push the class itself. Instead you have to push the object of a class. So, do - naves.push_back(nave());. Notice the ()Mahesh 2012-04-04 20:01
@Mahesh Good catch! I had not seen that one - MPelletier 2012-04-04 20:02
that work, thanks for the help = - Mete 2012-04-04 20:02
Be careful with vectors. If the object you want to put in is big, you should put in pointers to them instead, such as vector<nave*> naves;MPelletier 2012-04-04 20:05
@MPelletier That depends on whether objects should be shared. If objects are only to be accessed through the vector, you might as well put them there, even when they are big. The exception is when elements need to be moved withing the vector a lot. Or, when memory is so fragmented that a single big chunk of memory needed for the vector cannot be found, but the smaller chunks for individual objects can, but this situation is a probable indication of bigger problems in your code anyway - Branko Dimitrijevic 2012-04-04 20:18


2

Do this:

vector<nave> naves;
naves.push_back(nave());
  • The old line: vector<nave> naves(); was interpreted as a function declaration.
  • The old line: naves.push_back(nave); did not actually instantiate nave.
2012-04-04 20:05
by Branko Dimitrijevic
Ads