[英]Segmentation fault in push_back for a 2d vector
I'm learning c++ and I have a problem with a segmentation fault. 我正在学习c ++,我遇到了分段错误的问题。 In my project I want to read from a File into a 2d Vector of char.
在我的项目中,我想从一个文件读入一个2d的char矢量。 The Vector is
std::vector<std::vector<char>> gamearea;
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++;
}
}
This is my read file function and the debugger (I use gdb) says by push_back
is a segmentation fault. 这是我的读取文件函数和调试器(我使用gdb)说
push_back
是一个分段错误。
Can someone help me? 有人能帮我吗? I can't find the problem.
我找不到问题。
You need to first push back into the first vector a std::vector<char>
because by default the gamearea vector is empty, so when accessing gamearea[i] you end up accessing out of bounds (since gamearea has 0 elements inside it) 你需要首先将第一个向量推回到
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++;
}
}
Here is an example of properly reading in and updating your vector, given that it is empty: 这是一个正确读入和更新矢量的示例,只要它是空的:
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()));
}
Note we don't need to test for eof()
. 注意我们不需要测试
eof()
。 Also, all we need to do is call push_back
an entire string of data using the two argument std::vector constructor that takes two iterators. 另外,我们需要做的就是使用带有两个迭代器的两个参数std :: vector构造函数来调用
push_back
整个数据字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.