当我尝试在 Ubuntu 14.04 终端上运行这个程序时,我遇到了一个段错误(核心转储)错误。它编译正确但是当我运行程序时它给我一个段错误(核心转储)。我知道问题出在嵌套的 for 循环 block 上,因为当我删除该部分时,
for(int i = 0; i < 500; i++){
for(int j = 0; j < 500; j++){
map[i][j] = "unknown";
}
}
程序运行良好,但如果我包含上面的代码块,它就不行了。以下是正在进行的整个程序:
#include<iostream>
#include<string>
#include <stdlib.h>
#include <vector>
#include <iomanip>
using namespace std;
int moves = 0;
string input;
vector< vector<string> > map;
int main(int argc, char **argv) {
for(int i = 0; i< 500; i++){
for(int j = 0; j< 500; j++){
map[i][j] = "unknown";
}
}
while ( 1 ) {
getline(cin, input);
cout << "#"<< input[0] << endl;
cout << "#"<< input[2] << endl;
cout << "#"<< input[4] << endl;
cout << "#"<< input[6] << endl;
cout << "#"<< input[8] << endl;
cout << "forward" << endl;
}
for(int i = 0; i< map.size(); i++){
for (int j = 0; j < map.size(); j++){
cout << "#" << map[i][i] << endl;
}
}
return 0;
}
有哪位专家可以帮助找出问题所在?
最佳答案
你的片段
for(int i = 0; i < 500; i++){
for(int j = 0; j < 500; j++){
map[i][j] = "unknown";
}
}
尝试访问 vector 中不存在的元素。访问 vector 外部的元素不会自动创建它们(与 map 不同)。
要么使用 vector::push_back
插入元素,要么在循环之前调用 vector::resize
。
关于c++ - 段错误(核心转储)- 具有多维 vector 的循环 C++98,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28473015/