代码只输出一次 std::vector,而不是多次输出

Code only outputs std::vector one time instead of wanted multiple times

本文关键字:输出 vector 一次 代码 std      更新时间:2023-10-16

所以我的问题如下:我想编写一个基本的生活模拟游戏。因此,我使用 std::vector 来保存当前状态并计算下一个状态。一会儿就把所有的东西放在一起((。我正在为每个值做 std::cout,格式化为矩阵。问题是,我只得到一个"矩阵"作为输出,而不是预期的多个。

我还尝试在计算下一个状态后输出文本(所以在 nextCells=currentCells 之前和之后(,这不起作用,而在计算 for(( 循环中输出文本是有效的。

我不知道该怎么办了。感谢任何形式的帮助!

我尝试在计算下一个

状态后输出文本(所以在下一个单元格=当前单元格之前和之后(,这不起作用,而在计算 for(( 循环中输出文本是有效的。

#include <iostream>
#include <vector>
#include <unistd.h>
#define DIMX 10
#define DIMY 10
int countCells(std::vector<std::vector<int>> currentGrid, int x, int y);
int main() {
    std::vector<std::vector<int>> currentCells(DIMX, std::vector<int>(DIMY));
    std::vector<std::vector<int>> nextCells(DIMX, std::vector<int>(DIMY));
    int count = 0;
    nextCells = currentCells;
    while(true) {
        count++;
        for(int i=0;i<=DIMX-1;i++) {
            for(int j=0;j<=DIMY-1;j++) {
                std::cout << currentCells[i][j];
                std::cout.flush();
            }
            std::cout << "n";
        }
        for(int i=0;i<=DIMX-1;i++) {
            for(int j=0;j<=DIMY-1;j++) {
                int aliveCells = countCells(currentCells, i, j);
                if(currentCells[i][j]==0) {
                    if(aliveCells==3) {
                        nextCells[i][j]=1;
                    } else {
                        nextCells[i][j]=0;
                    }
                } else {
                    if(aliveCells>3) {
                        nextCells[i][j]=0;
                    } else if(aliveCells<2) {
                        nextCells[i][j]=0;
                    } else {
                        nextCells[i][j]=1;
                    }
                }
            }
        }
        currentCells = nextCells;
        if(count>=5) {
            return 0;
        }
    }
}
int countCells(std::vector<std::vector<int>> currentGrid, int x, int y) {
    int aliveCounter;
    if(x==DIMX || x==0 || y==DIMY || y==0) {
        return 0;
    }
    if(currentGrid[x-1][y-1]==1) {
        aliveCounter++;
    } else if(currentGrid[x-1][y]==1) {
        aliveCounter++;
    } else if(currentGrid[x-1][y+1]==1) {
        aliveCounter++;
    } else if(currentGrid[x][y-1]==1) {
        aliveCounter++;
    } else if(currentGrid[x][y+1]==1) {
        aliveCounter++;
    } else if(currentGrid[x+1][y-1]==1) {
        aliveCounter++;
    } else if(currentGrid[x+1][y]==1) {
        aliveCounter++;
    } else if(currentGrid[x+1][y+1]==1) {
        aliveCounter++;
    }
    return aliveCounter;
}

您的代码生成一个超出向量范围的异常,出于优化原因,该异常可能不会在发布模式下引发。当 countCells 被调用为 y = 9 或 x = 9 时

currentGrid[x+1][y+1]

超出范围。请注意

  v = std::vector<int>(10,0) can be called from v[0] to v[9]; not v[10],

这将超出范围。