将整个文件读入行向量的最有效方法
Most efficient way to read an entire file into vector of lines
我正试图找到一种更有效的方法将整个文件读取为行向量,定义为std::vector<std::string>
。
目前,我已经写了幼稚的:
std::ifstream file{filepath};
std::vector<std::string> lines;
std::string line;
while(std::getline(file, line)) lines.push_back(line);
但是我觉得push_back
中额外的复制和每行的向量重新分配对效率非常不利,我正在寻找一种更现代的c++类型的方法,例如在复制字节时使用流缓冲区迭代器:
std::ifstream file{filepath};
auto filesize = /* get file size */;
std::vector<char> bytes;
bytes.reserve(filesize);
bytes.assign(std::istreambuf_iterator{file}, istreambuf_iterator{});
是否有这样的方式,我可以读取文本文件在行成一个矢量?
有一种非常有趣且相对较新的方法——range。你可以阅读Eric Niebler写的非常有趣的文章:
关于快速getlines替代
的Out参数、Move语义和状态算法输入迭代器与输入范围
下面的代码可以工作。
struct FileContents
{
// Contents of the file.
std::string contents;
// Each line consists of two indices.
struct line { std::string::size_type begin; std::string::size_type end;};
// List of lines.
std::vector<line> lines;
};
void readFileContents(std::string const& file,
FileContents& fileContents)
{
std::ifstream ifs(file);
if ( !ifs )
{
// Deal with error.
return;
}
// Get the size of the file.
ifs.seekg(0, std::ios::end);
std::fstream::pos_type size = ifs.tellg();
// Reserve space to read the file contents.
fileContents.contents.assign(static_cast<std::string::size_type>(size), ' ');
// Read the file contents.
ifs.seekg(0, std::ios::beg);
ifs.read(&fileContents.contents[0], size);
ifs.close();
// Divide the contents of the file into lines.
FileContents::line line = {0, 0};
std::string::size_type pos;
while ( (pos = fileContents.contents.find('n', line.begin)) != std::string::npos )
{
line.end = pos+1;
fileContents.lines.push_back(line);
line.begin = line.end;
}
line.end = fileContents.contents.size();
if ( line.begin < fileContents.contents.size() )
{
fileContents.lines.push_back(line);
}
}
相关文章:
- 在C++中初始化向量映射的最有效方法
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- C++有效地找到向量中第一个最接近的匹配值?
- 如何有效地操作满足给定谓词的向量中的所有项目?
- 检查两个向量是否并行的最有效方法
- 当表示为对象的一维向量时,有效地旋转 NxM 矩阵 (C++)
- 如何有效地实现将向量的数据分配给多个变量?
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 如何在C++中有效地将数组移动到向量
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 如何有效地用第二个值对向量对进行分组
- 从长(且合理)稀疏向量中选择随机元素的最有效方法是什么?
- 如何在 CUDA 中(有效地)将大量向量相互比较
- 基于整数向量执行位排列的有效方法?
- 如何使用C++有效地合并排序与向量
- C++:检查向量中的元素是否大于另一个具有相同索引的元素的有效方法?
- 如何有效地规范化向量C++
- remove_if然后擦除对向量有效吗
- 将一个STL向量有效地分配给另一个STL矢量(WSL问题)
- c++向量有效地添加元素