Sign in to follow this  

vector with unknown # of objects

This topic is 3728 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
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[i]<<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

This topic is 3728 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this