c++ - 段错误(核心转储)- 具有多维 vector 的循环 C++98

标签 c++ vector segmentation-fault c++98

当我尝试在 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/

相关文章:

c# - Easy Trig - 将物体移动到某个位置

c - SIGSEGV 处理程序中的段错误

c++ - 获取 QString 时出现段错误

c# - 使用 C# 测试 C++ 代码时的代码覆盖率

c++ - 类型位长度和特定于体系结构的实现

c++ - 为什么在 gcc 构建的 Mingw 端口中有两个 bin 文件夹?

c++ - 指向指针数组的指针导致段错误

c++ - 全局重载运算符 new/new[] delete/delete[] C++

c++ - 我可以为迭代器赋值吗?

algorithm - 从两个向量计算方向角?