gpt4 book ai didi

c++ - 二维 vector 的 push_back 中的段错误

转载 作者:行者123 更新时间:2023-11-30 02:30:30 25 4
gpt4 key购买 nike

我正在学习 C++,但遇到了段错误问题。在我的项目中,我想从一个文件中读入一个 char 的二维 vector 。 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 表示是段错误。

有人可以帮助我吗?我找不到问题所在。

最佳答案

您需要先推回第一个 vector a std::vector<char>因为默认情况下 gamearea vector 是空的,所以当访问 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++;
}
}

关于c++ - 二维 vector 的 push_back 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38562067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com