【问题标题】:Segmentation fault (core dump) - for loop with multidimensional vector C++98分段错误(核心转储) - 具有多维向量 C++98 的 for 循环
【发布时间】:2015-02-12 08:50:25
【问题描述】:

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

有哪位专家可以帮助确定问题吗?

【问题讨论】:

  • 除了回答,还要明白std命名空间中已经定义了“map”。它是标准容器之一。你所做的类似于 list>vector;
  • 感谢tipaye,帮了大忙!

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


【解决方案1】:

你的sn-p

for(int i = 0; i < 500; i++){
   for(int j = 0; j < 500; j++){
     map[i][j] = "unknown";
   } 
 }

尝试访问向量中不存在的元素。访问向量之外的元素不会自动创建它们(与地图不同)。

在循环之前使用vector::push_back 插入元素或调用vector::resize

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2017-02-25
    • 2016-07-12
    • 2018-03-16
    相关资源
    最近更新 更多