-1
我新的矢量編程,所以我的代碼是馬車:寫入2D矢量,崩潰我的程序
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::ifstream in("input.txt");
std::vector<std::vector<int> > v, w;
if (in) {
std::string line;
while (std::getline(in, line)) {
v.push_back(std::vector<int>());
for(int x=0; x<line.size(); x++){
v.back().push_back((int)line[x] - (int)'0');
}
}
}
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++)
std::cout << v[i][j] << ' ';
std::cout << '\n';
}
int size = v.size(); //because its a square matrix
w = v; //w is our temp vector for storing new values;
int alive =0;
int z=0;
for (int i=0;i<size;i++)
{
for (int j=0;j<size; j++)
{
alive = 0;
for(int c = -1;c<2; c++)
{
for(int d = -1; d<2 ; d++)
{
if(!(c==0 && d == 0))
{
z = v[i+c][j+d];
if(z)
++alive;
}
}
if(alive<2) w[i].push_back(0);
else if(alive == 3) w[i].push_back(1);
else w[i].push_back(0);
}
}
}
return 0;
}
我想我分配值到我的第二個變量是錯誤的。我的程序從沿線的輸入文件上寫着:
1010101
0101010
1010101
,並分析其鄰國(生活不能玩的遊戲),我想我應該用w.push_back()
後寫入第二矢量w
,但我不知道在2D矢量的語法上。有沒有更好的方法來推動變量?
'z = v [i + c] [j + d];' - 將其更改爲'z = v.at(i + c).at(j + d);' - 然後診斷正在拋出的'std :: out_of_range'異常。 – PaulMcKenzie