所以我的目标是从文件中读入并存储单个字符(它们是基因组序列)。这些文件非常大,基本上看起来像这样:
>gi|188033402|emb|CU859091.1| A BAC library has been constructed from PN40024...
AGCTCCTTTTTAAAACAACATTCAAGAAATTGGAGTTTGGCATTTTTACAAAGAGCATATTCAGCTCTGG
GAAGTATTTCTTGAGCAAAGAGGAGCGAAAATAGATCCTAAATGTTCCCCAGATTTTCCCCAGATTCCAA
可以完全忽略以“>”字符开头的行。所以基本上我只想要“AGCTCCTTTTTA...”部分。
我的代码适用于较小的文件,但适用于较大的文件时会崩溃。我想弄清楚这里的内存问题是什么以及如何解决它。运行文件时出现的错误是:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
这是我读取单个字符并将它们存储到 vector 中的简化代码:
int main(int argc, char * argv[])
{
ifstream file (argv[1]);
vector<char> sequenceA; // to store the single characters
string line; // to grab lines from the file
char c; // to grab the single character from the file
// go through the file
while(getline(file,line))
{
//store the line
stringstream stream(line);
// go through and grab each single character in the line
while(stream.get(c))
{
if(c == '>')
{
// break and continue to the next line
break;
}
else
{
// add the character to the list
sequenceA.push_back(c);
}
}
}
我正在浏览 stackoverflow 上的其他“std::bad_alloc”帖子,但似乎找不到可以帮助我解决问题的帖子,因此非常感谢您的帮助!如果你不知道,我对编程还是很陌生,非常感谢你的解释。
非常感谢!
最佳答案
这意味着程序最终会请求一个足够大的连续内存块,以至于系统无法提供它。
如果您坚持自己的方法,快速修复可能是使用 deque
而不是 vector
。
关于c++ - std::bad_alloc 将文本文件中的单个字符存储到 vector C++ 中时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49849797/