Home > Software engineering >  How can I add a given amount of 2D vectors into a 3D vector?
How can I add a given amount of 2D vectors into a 3D vector?

Time:10-06

I am currently developing a maze generator and splitting it up into cells which I aim to add up to create a maze. The cells are 2D vectors, and the 3D vector is supposed to engulf all of the cells, given a certain number of rows and columns to make up the maze. I tried looping through the 3D vector and pushing back the 2D vectors; however, this method does not seem to work, leading to a compiler error. Below is the code that I am currently using - this maze uses classes. How could the approach to fill the 3D vector be fixed so that the maze is correctly generated?


std::vector<std::vector<std::vector<char> > > maze::matrix (int rows, int columns, std::vector<std::vector<char> > cell)  {

    std::vector<std::vector<std::vector<char> > > maze;

    for (int i = 0; i < rows; i  ) {
        
        maze.push_back(std::vector<std::vector<char> >());

        for (int j = 0; j < columns; j  ) {

            maze.at(i).push_back(cell);

        }
    }

    return maze;

}

CodePudding user response:

First, as suggested, you should make aliases for the types, so that you can more clearly see the issue:

#include <vector>

// Create aliases
using Char1D = std::vector<char>;
using Char2D = std::vector<Char1D>;
using Char3D = std::vector<Char2D>;

int main()
{
  // Sample set of cells 
  Char2D cells = {{'x','y'},{'0','1'}};
  Char2D cells2 = {{'0','1'},{'x','y'}};

  // The maze to add the above cells
  Char3D maze;

 // Now add the cells to the maze
  maze.push_back(cells);
  maze.push_back(cells2);
}

That code adds 2 different Char2D cells to the maze.

The issue with your code is that you were basically calling push_back with the wrong types -- you were calling maze[i].push_back, but maze[i] is already a Char2D, so you were trying to push_back a Char2D into a Char2D.

More than likely, your code was not following your specification of adding 2D vectors to the 3D vector.

CodePudding user response:

Please also include the unexpected behavior you get. In this case, this code won't compile.

maze is a vector<vector<vector<char>>> i.e. 3D vector

maze.at(i) is a vector<vector<char>> i.e. 2D vector

You are trying to push_back(cell), where cell is a 2D vector.std::vector::push_back takes an element of the vector, so for a 2D vector it takes a 1D vector i.e. maze.at(i).push_back(std::vector<char>{}).

  • Related