c++pointersvector

Can I have a Vector of pointers in a Object *** p?


Here's my question: I have a multi-dimensional array in which I'm trying to put some objects derived from class Block. I have this multi-dimensional array declared the following way:

Block ***arrTerrain;

where the first '' is for the lines, the second '' is for the columns and the third is for the pointer to object inside the position (let's assume it's an object called FreeTerrain).

I initialize it this way:

this->arrTerrain = new Block**[a]; 

for(int i=0;i < a ;i++){
    arrTerrain[i] = new Block*[l];
}

for(int i=0;i<a;i++)
    for(int j=0;j<l;j++)
        arrTerrain[i][j] = new FreeTerrain;

I'm supposed to have soldiers in a given position (class soldier derives from block as well). If I want to put 2 soldiers in the same position, I lose the pointer to the first one (obviously). So I thought of having in each position a vector of Blocks or some sort but I find this difficult to implement.

Can anyone of you guys help me out?

Thanks in advance!


Solution

  • Answer is yes, you can make a vector of (almost) anything.

    Now the the implicit question is "SHOULD I make a vector of Object ***" and the answer is nooooooo.

    First off, you should only use pointers when you have to. If you have an array of FreeTerrain that are all the same class, don't use new to them just make an array of FreeTerrain.

    And you shouldn't hold an array in a vector, that's just asking for trouble.

    Overall you should just use a std::vector<std::vector<FreeTerrain>>.

    Edit: From the comments below, if you really need to use pointers (say, to have polymorphic references) use a unique pointer:

     std::vector<std::vector<std::unique_ptr<FreeTerrain>>> v;