我正在寻找一种将文件中的字符串存储到字符串 vector 中的快速方法,这样我就可以提前保留行数。做这个的最好方式是什么?我应该先继续新行字符,还是只获取文件的总大小,然后只保留说大小/80,以便粗略估计要保留的内容。理想情况下,我不希望每次都必须重新分配 vector ,这会大大降低大文件的速度。理想情况下,我会提前计算项目的数量,但我应该通过以二进制模式打开计算新行然后重新打开来做到这一点吗?这似乎很浪费,对此有些想法感到好奇。还有一种方法可以使用 emplace_back 摆脱下面 getline 代码中的临时字符串。我确实看到了以下 2 个用于提前计算行数的实现 Fastest way to find the number of lines in a text (C++)
std::vector<std::string> vs;
std::string somestring;
std::ifstream somefile("somefilename");
while (std::getline(somefile, somestring))
vs.push_back(somestring);
我还可以做一些事情来提前获得总大小,我可以直接将这种情况下的 char* 转换为 vector 吗?这可以追溯到我的 reserve 提示,即说 size/80 或某个常量以预先为 reserve 提供估计大小。
#include <iostream>
#include <fstream>
int main () {
char* contents;
std::ifstream istr ("test.txt");
if (istr)
{
std::streambuf * pbuf = istr.rdbuf();
//which I can use as a reserve hint say size / 80
std::streamsize size = pbuf->pubseekoff(0,istr.end);
//maybe I can construct the vector from the char buf directly?
pbuf->pubseekoff(0,istr.beg);
contents = new char [size];
pbuf->sgetn (contents,size);
}
return 0;
}
最佳答案
与其浪费时间提前计算行数,我只需要 reserve()
一个初始值,然后开始压入实际的行,如果你碰巧压入了保留的项目数只需 reserve()
一些空间,然后继续进行更多推送,根据需要重复。
关于C++ 使用 reserve 和可能的 emplace_back 从文件中存储 vector<std::string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17870998/