vector with unknown # of objects

Started by
3 comments, last by geo2004 16 years, 6 months ago
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;
Advertisement
have you tried vContainers.resize( howMany ); ?
That should insert new objects at the end of the vector using their default constructor.
[reference]
You can use push_back() without first having to create a named instance of a cContainer like this:

vContainers.push_back(cContainer());


HTH
you should drop the lowercase c from the front of your type names. It adds nothing.
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)

This topic is closed to new replies.

Advertisement