How to initialize a 2D vector with pointers in c++?

162 Views Asked by At

So I am trying to initialize a 2D vector of pointers/matrix of pointers(/3d vector?) in c++. A 2D matrix of pointers to cell objects. When running the code I get this error:

error: no matching function for call to ‘std::vectorstd::vector<Cell* >::push_back(std::vector&)’
17 | matrix.push_back(temp);

Note:Cell is a class

City.hh:

std::vector <std::vector <Cell*>> matrix;
City(unsigned int M, unsigned int N);   

City.cc:

#include "City.hh"
City::City(unsigned int N, unsigned int M)
{
    // size of "matrix"
    this->M = M;
    this->N = N;
    
    for(unsigned int i = 0; i < M; i++)
    {
        vector <Cell> temp;
        for(unsigned int j = 0; j < N; j++)
        {
            Cell cell = Cell();
            temp.push_back(cell);
        }
        matrix.push_back(temp);
    }
}
1

There are 1 best solutions below

0
digito_evo On

I would suggest you keep your objects close to each other (due to various reasons) by avoiding the use of pointers and do this instead:

std::vector< std::vector< Cell > > matrix( M, std::vector< Cell >( N ) );