[英]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.