C ++,如何将向量复制到向量向量中?

时间:2018-11-19 01:45:58

标签: c++ vector copy

我认为以下代码可以工作,这是我的代码的简化版本:

az group deployment create --resource-group 'joywebapp' --template-uri 'https://xxxxxx.blob.core.windows.net/templates/azuredeploy.json?sp=r&st=2018-11-19T01:36:04Z&se=2018-11-19T09:36:04Z&spr=https&sv=2017-11-09&sig=xxxxx&sr=b'

但是,似乎它并没有改变网格的值,现在它的坐标之一应该是星形的,但是,所有网格包含的都是它的原始值。

相关输出:

#include <iostream>
#include <vector>

int main()
{
    int xCoordMovement, yCoordMovement;
    int rows, cols;
    char point = '*';

    std::cout << "enter number of rows";
    std::cin >> rows;
    cols = rows;

    std::vector<std::vector<char>> grid(rows, std::vector<char>(cols, '0'));
    std::vector<char> flattenedGrid;

    for (int x = 0; x < rows; x++)
    {
        for (int y = 0; y < cols; y++)
            std::cout << grid[x][y];
        std::cout << std::endl;
    }
    std::cout << "input for x coord: ";
    std::cin >> xCoordMovement;
    std::cout << "input for y coord: ";
    std::cin >> yCoordMovement;

    for (int x = 0; x < rows; x++)
        for (int y = 0; y < cols; y++)
            flattenedGrid.push_back(grid[x][y]);

    flattenedGrid[((cols * yCoordMovement) - (rows - xCoordMovement)) - 1] = point;

    std::cout << flattenedGrid.size() << std::endl;

    for(int i = 0; i < flattenedGrid.size(); i++)
        std::cout << flattenedGrid[i];

    std::cout << std::endl;

    for (int x = 0; x < rows; x++)
        for (int y = 0; y < cols; y++)
           for (int i = 0; i < flattenedGrid.size(); i++)
                grid[x][y] = flattenedGrid[i];


    for (int x = 0; x < rows; x++)
    {
        for (int y = 0; y < cols; y++)
            std::cout << grid[x][y];
        std::cout << std::endl;
    }

    std::cin.ignore();
    std::cin.get();

    return 0;
}

所需的输出:

00000 
00000 
00000 
00000 
00000

这是我希望将向量的值分配给向量的向量的位:

00000
000*0
00000
00000
00000

1 个答案:

答案 0 :(得分:0)

您需要对代码进行几处更改:

  • 首先,当您将point分配给flattenedGrid的元素时

更改:

 flattenedGrid[((cols * yCoordMovement) - (rows - xCoordMovement)) - 1] = point;

至:

flattenedGrid[(yCoordMovement) + (rows * xCoordMovement)] = point;
  • 第二,当您用元素grid重新填充flattenedGrid

更改:

for (int x = 0; x < rows; x++)
    for (int y = 0; y < cols; y++)
        for (int i = 0; i < flattenedGrid.size(); i++)
             grid[x][y] = flattenedGrid[i];

至:

for (int x = 0; x < rows; x++)
        for (int y = 0; y < cols; y++)          
                grid[x][y] = flattenedGrid[rows * x + y];
相关问题