当我尝试在Ubuntu 14.04终端上运行此程序时出现分段错误(核心转储)错误。它已经正确编译,但是当我运行程序时,它给我一个分段错误(核心转储)。我知道问题出在那儿的嵌套for循环块是因为当我删除该部分时,

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

07-26 09:43
查看更多