I have a base class, Organism, with 2 derived classes, Ant and Doodlebug. This is for a predator-prey problem. I want to have a 2d vector of type Base class, but be able to assign elements of the derived class. The idea being that this will represent the state of the world in a 20 X 20 character map where if the element is the base, the char is ‘ ‘, whereas it will be a different char if the element is derived.
I read about how to do it if its one dimensional vector, but I couldn’t find the proper syntax of declaring a pointer to a 2d vector. Here’s what I have, I got errors if I tried to put:
vector < vector<Organism*> > state(20, vector<Organism*>(20));
but this is what compiles but prints out a field of numbers instead of the characters:
vector < vector<Organism> > state(20, vector<Organism>(20));
string line;
int stateline = 0;
while(getline(ini_state_file, line))
{
for(int i = 0; i < line.size(); i++)
{
if(line[i] == 'o')
state[stateline][i] = Ant();
else if(line[i] == 'X')
state[stateline][i] = Doodlebug();
}
stateline++;
}
Not forget to free memory. When your work with this vector will be ended, you must free memory, example.
Or use iterators or algorithm as for_each instead indexes.
If you want to use smart pointers, you shouldn`t free memory.