二维向量的push_back中的分段错误

Segmentation fault in push_back for a 2d vector

本文关键字:back 分段 错误 push 二维 向量      更新时间:2023-10-16

我正在学习c++,但遇到了分段错误的问题。在我的项目中,我想从一个文件读取到一个二维矢量的字符。矢量为std::vector<std::vector<char>> gamearea;

void Structure::readFile(const std::string filename) 
{ 
    std::ifstream file(filename.c_str()); 
    if (!file.is_open()) 
    { 
       std::cerr << "Error opening file: " << filename << std::endl;    
       exit(1); 
    } 
    std::string line; 
    int i = 0; 
    while (true) 
    { 
       std::getline(file, line); 
       if (file.eof()) 
       { 
          break; 
       } 
       for (size_t j = 0; j< line.length(); j++) 
       { 
           gamearea[i].push_back(line[j]); 
       } 
       i++; 
    } 
}

这是我的读取文件函数,调试器(我使用gdb)说push_back是分段错误。

有人能帮我吗?我找不出问题。

您需要首先将std::vector<char>推回到第一个向量中,因为默认情况下游戏区域向量是空的,所以当访问游戏区域[i]时,您最终会访问越界(因为游戏区域中有0个元素)

void Structure::readFile(const std::string filename) 
{ 
std::ifstream file(filename.c_str()); 
if (!file.is_open())  {
 std::cerr << "Error opening file: " << filename << std::endl; exit(1);
} 
std::string line; int i = 0; 
while (true) { 
    std::getline(file, line); 
    if (file.eof()) { break; } 
    // NOTICE HERE 
    // We add a new vector to the empty vector 
    std::vector<char> curArea;
    gamearea.push_back(curArea);

    for (size_t j = 0; j< line.length(); j++) {
       gamearea[i].push_back(line[j]); 
    } 
    i++;
  } 
}

以下是一个在向量为空的情况下正确读取和更新向量的示例:

void Structure::readFile(const std::string filename) 
{ 
   std::ifstream file(filename.c_str()); 
   if (!file.is_open())  {
       std::cerr << "Error opening file: " << filename << std::endl; 
   return;
   std::string line; 
   while (std::getline(file, line)) 
       gamearea.push_back(std::vector<char>(line.begin(), line.end()));
}

实际示例

注意,我们不需要测试eof()。此外,我们所需要做的就是使用带有两个迭代器的两个参数std::vector构造函数来调用push_back一整串数据。