我正在学习C++,并且遇到了分段错误问题。在我的项目中,我想从一个文件读入char的二维矢量。 矢量是std::vector<std::vector<char>> gamearea;
2d向量push_back中的分段错误
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
说是分段错误。
有人可以帮助我吗?我找不到问题。
'gameArea [i] .push_back(line [j])' - 将此更改为'gameArea.at(i).push_back(line [j])',如果您现在得到'out_of_range'异常,而不是分段错误。换句话说,没有'gameArea [i]',因为'i'是一个无效索引。 – PaulMcKenzie
你能告诉我为什么我是一个无效索引,我需要改变什么?我想在向量中保存游戏区域的行,并且在其他功能中,我需要游戏中的事物的确切位置,如图和框。我认为我可以用行来说,它和行[j]保存在矢量中的字符,以便我知道字符的行和列。 – Lisa