繁体   English   中英

push_back中的分段错误为2d向量

[英]Segmentation fault in push_back for a 2d vector

我正在学习c ++,我遇到了分段错误的问题。 在我的项目中,我想从一个文件读入一个2d的char矢量。 Vector是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>因为默认情况下,gamearea向量是空的,所以当访问gamearea [i]时你最终访问越界(因为gamearea里面有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整个数据字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM