二维向量的push_back中的分段错误
Segmentation fault in push_back for a 2d vector
我正在学习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
一整串数据。
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 在线编译器中的分段C++没有打印消息
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)