Hello, I am new, and have been searching the forums for answers, and I don't know any programmers. If I missed this somewhere I apologize. I found something close, but not handling what I wanted to try. Here's the scoop:
In trying to teach myself C++ I was trying to make a little simulation program in the console where these two little "germ" kind of things wander around a multidimensional array and when they bump into each other one eats the other or they multiply or something. I am hand-coding the two instances of the class, and it works alright.
What I would like to do, is use CIN and the console to type in a name for a germ, such as "Bob" for this example, and have that be the name of a new instance for the class of 'germs' I have created, so I can easily add 3, 10, or 20 new little critters running around. But I have "C++ programming in easy steps" by Mike MCGrath, which is great for a beginner like me, and it doesn't cover that scenario.
What I would like to do is instead of saying for a "Germ" class...
Germ Bob;
I would like to do something like this....(very simplified here)
string name;
cin << name;
Germ name;
This is apparently the wrong thing to do, so I was wondering if anyone had any suggestions? Thank you for taking the time to read this. Again, I'm just puttering with this code and never took any classes so this all might sound a little dopey! Thanks again
A vector is just like an array, but it can change sizes at runtime.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
vector<Germ> Germs;
while (userIsEnteringNames())
{
Germs.push_back(Germ(name, x, y));
}
//later
for (unsigned i = 0; i<Germs.size(); i++)
{
if (Germs[i].isDead())
{
Germs.erase(Germs.begin()+i);
i--;
}
}
A vector would be easier to iterate through all the Germs, and you wouldn't have to deal with storing all the names to access the Germs (or using iterators in place of integers).
I am still trying to get the vectors to work I am still struggling with it, however I seem to have gotten the map to work. I didn't know about maps-I love them! They remind me of hashes in Perl which make sense to me already.
As well they should. A vector just works like an array in Perl (@), that is, you can add and remove elements, changing it's size dynamically. If your germs don't need names and simple indexes (or id's) will do, then a vector would probably be easier, but that's just me...