Sign in to follow this  

Multiple object creation and vectors

This topic is 2856 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

What's up GameDevers, What would be the typical algorithm for using a loop to create multiple objects of type 'someClass', assigning some values to their members, and pushing their pointers' onto a vector?

Share this post


Link to post
Share on other sites

class foobar;

struct foobarMaker {
foobar* operator() {
foobar *tmp = new foobar;
tmp->a = rand()%100;
tmp->b = rand()%20;

return tmp;
}
};

vector<foobar*> foos;
generate_n( back_inserter( foos ), 10, foobarMaker() );

// psuedo code:
for_each( foos.begin(), foos.end(), delete );

Share this post


Link to post
Share on other sites
Quote:
Original post by nGamer
and pushing their pointers' onto a vector?


Why do you think you want to store pointers in the vector, instead of just storing instances directly?

Share this post


Link to post
Share on other sites
If you want to create objects in a loop and push them onto a vector, then the "typical" way is to do exactly that:
// Loop
for(int i = 0; i < 100; ++i)
{
// Additional logic
if(!shouldCreate(i))
continue; // or maybe 'break'

// Object "creation", factory also handles member assignment
foobar* foo = foobarFactory(i /*, other params */);

// Vector push
foos.push_back(foo);
}

Share this post


Link to post
Share on other sites

This topic is 2856 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