Need info on Dynamic array of classes

I am trying to create a dynamic array of classes that do not have default constructors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void Battlefield::Battle()
{
          unsigned NumMnstrsSpawned=(rand()%(maxspawn-minspawn+1)+minspawn);
          for(unsigned int i=0;i<NumMnstrsSpawned;i++)
          {
                    Monster* spawn= new Monster[i];
                    spawn[i]=//this is where i use functions to get random stats for my constructors.        
            
          }

}


Last edited on
fixed it with this
Monster** spawn= new Monster*[NumMnstrsSpawned];
spawn[i]->randomHp();
You fixed it, you say? I take it you didn't actually try to run it?
I spoke to soon. Any hints?
If your Monster objects can be copied and it's fine for all elements to be a copy of one monster, you can do this:
vector<Monster> spawn(NumMnstrsSpawned,Monster(pa,ra,me,te,rs));

If Monster can be moved, do this:
1
2
vector<Monster> spawn;
for (uint i=0;i<NumMnstrsSpawned;i++)spawn.emplace_back(pa,ra,me,te,rs);


If a monster can't even be moved, you can do this:
1
2
list<Monster> spawn;
for (uint i=0;i<NumMnstrsSpawned;i++)spawn.emplace_back(pa,ra,me,te,rs);


Alternatively, you can use a vector of pointers:
1
2
3
typedef std::unique_ptr<Monster> UMonster;
vector<UMonster> spawn;
for (uint i=0;i<NumMnstrsSpawned;i++)spawn.emplace_back(new Monster(pa,ra,me,te,rs));


Before C++11, implementations of ptr_vector (and similar containers) existed to solve this problem.
Thanks alot. I'll save this. I just finished all of the basics in the manual and haven't went into the templates and vectors section just yet.
I did get my file to run and work as good as i can tell using arrays. I will use vectors when I understand them enough. is there a problem with using this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Battlefield::Battle()
{
          unsigned NumMnstrsSpawned=rand()%(maxspawn-minspawn+1)+minspawn;
          Monster** spawn=NULL;
          spawn= new Monster*[NumMnstrsSpawned];

          for(unsigned int i=0;i<NumMnstrsSpawned;i++)
          {
                    spawn[i]=new Monster("Talimar", "Lich", 10,100,50);//replace this constructor with functions to randomly generate figures
          }
          
          for(unsigned i=0;i<NumMnstrsSpawned;i++){
                    delete spawn[i];}
          delete [] spawn;

}
That works as long as no exceptions are involved. The main problem is that it is unnecessarily complicated, but for now it'll do.
Topic archived. No new replies allowed.