代码只输出一次 std::vector,而不是多次输出
Code only outputs std::vector one time instead of wanted multiple times
所以我的问题如下:我想编写一个基本的生活模拟游戏。因此,我使用 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],
这将超出范围。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- 请解释"函数1(p1,p2,p3);"的输出
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 代码只输出一次 std::vector,而不是多次输出
- swig perl typemap(out) std::vector<std::string> 在 perl 中不返回所需的输出
- 将std::vector作为输入/输出引用参数传递时丢失了一些数据
- 当字符串最初位于 std::vector 中时,c_str() 会产生不同的输出
- 我可以使用 opencv 函数(如 cv::multiply 和 std::vector<cv::Mat> 作为输入和输出参数吗?
- 如何将 vector 传递给将自定义对象作为参数的重载输出流
- 如果我使用 vector::begin() 而不是 std::back_inserter(vector) 来输出set_
- [swig-JavaScript]是否支持std::vector<std::string>*作为输出?
- 如何在 C++ 中以 vector<vector<pair<int,int>>> 中获取输入并显示输出?
- 将bitset成员函数count的输出放入vector很慢
- 将数组赋值给std::vector会产生不正确的输出
- 从.txt读取int,将其保存到vector,然后保存到输出文件