簡體   English   中英

C ++,如何將向量復制到向量向量中?

[英]c++, how do I copy a vector into a vector of vectors?

我認為以下代碼可以工作,這是我的代碼的簡化版本:

#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

這是我希望將向量的值分配給向量的向量的一點:

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];

您必須對代碼進行幾處更改:

  • 首先,當您將point分配給flattenedGrid的元素時

更改:

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

至:

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

更改:

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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM