Jump to content
  • Advertisement
Sign in to follow this  
spitzervx

vector with unknown # of objects

This topic is 4034 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm just wondering if there was a way to create a vector which when you use the push_back() method, automatically creates a new instance of that class type? In the following piece of code, I got a vector to store some class objects but the problem is I had to manually create those objects first, then insert them. I want it so when vContainer expands, it automatically creates a new object of that class. Is that possible? //create container objects first cContainer Container1(1); cContainer Container2(2); //create a vector to hold the containers vector<cContainer> vContainers; //put the containers into the vector vContainers.push_back(Container1); vContainers.push_back(Container2); //access the objects inside the vector cout << vContainers.begin()->GetItem() << endl; cout << vContainers.end()->GetItem() <<endl;

Share this post


Link to post
Share on other sites
Advertisement
You can use push_back() without first having to create a named instance of a cContainer like this:


vContainers.push_back(cContainer());


HTH

Share this post


Link to post
Share on other sites
you should drop the lowercase c from the front of your type names. It adds nothing.

Share this post


Link to post
Share on other sites
Also, when accessing the objects in the vector, you can do it the same as you would an array:


vector<Container> Containers;
Containers.push_back(Containers(1));
Containers.push_back(Containers(2));

for(int i = 0;i<Containers.size();i++){
cout<<Containers<<endl;
}



This will print all the objects in that vector, regardless of its size (unless of course you only wanted to output the beginning and ending object, then your way will do)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!