简体   繁体   中英

How can I add a given amount of 2D vectors into a 3D vector?

I am currently developing a maze generator and splitting it up into cells which I aim to add up to create a maze, and each cell is a 2d vector where classes are employed. How can I add all of the corresponding 2d vectors to a 3d vector to generate the maze? Below is the code I have been employing.


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;

}

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.

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

maze is a vector<vector<vector<char>>> ie 3D vector

maze.at(i) is a vector<vector<char>> ie 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 ie maze.at(i).push_back(std::vector<char>{}) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM