Question

I am having trouble figuring out how i can store new object into a vector, and be able to pull that information out.

What i am trying to do is, storing different data from files in a series of objects, then going through these objects and pulling out the information.

I am looking for something like this:

vector<myClass> list;
while( i < nFiles)
{
   myClass *temp = new myClass;
   list.push_back(temp);       

   temp->setSomething();

   i++;
}

I want to have a different object for every nFile cycle, so i am able to later go through each object and pull the information out from each object.

I've tried pushing the temp to a vector but its giving me nothing but errors.

Is what i'm trying to do programatically correct? I can't get my head around this. Any sort of help would be much appreciated. Thank you.

Was it helpful?

Solution 3

Your vector should either be a vector of pointers to myClass, i.e.,

vector<myClass *> list;

Or your temp shouldn't be a pointer, i.e.,

myClass temp;

The latter means the whole temp object is copied when you do list.push_back (byte by byte).

OTHER TIPS

First a bit of vocabulary: You don't want to store classes in the array (actually, vector), you want to store objects. Objects are instances of classes.

Second, you've got the syntax of the while loop wrong. Look it up in a C++ book. Better use a for loop.

Third, always write MyClass the same way. Don't change lower-/upper case.

And finally, learn about the difference between pointer to objects and objects. The element type you specify when you declare the vector doesn't match the things you put into it.

the syntax is while (...) not (while ...) AND you cant say i=1 in the while loop parameters. What you wanna do is:

either :

 int i = 1;
 while (i < nFiles){
   //Do something
 }

OR

for (int i = 1; i < nFiles; i++){
  //Do something
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top