将文件读入std :: vector <char>的有效方法?

Ped*_*ino 36 c++ stl vector

我想避免不必要的副本.我的目标是:

std::ifstream testFile( "testfile", "rb" );
std::vector<char> fileContents;
int fileSize = getFileSize( testFile );
fileContents.reserve( fileSize );
testFile.read( &fileContents[0], fileSize );
Run Code Online (Sandbox Code Playgroud)

(这不起作用,因为reserve实际上没有在向量中插入任何东西,所以我无法访问[0]).

当然,std::vector<char> fileContents(fileSize)有效,但是初始化所有元素的开销(fileSize可能相当大).同样的resize().

这个问题与开销的重要程度无关.相反,我只是想知道是否有另一种方式.

wil*_*ell 59

规范形式是这样的:

#include<iterator>
// ...

std::ifstream testFile("testfile", std::ios::binary);
std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)),
                               std::istreambuf_iterator<char>());
Run Code Online (Sandbox Code Playgroud)

如果您担心重新分配,请在向量中保留空间:

#include<iterator>
// ...

std::ifstream testFile("testfile", std::ios::binary);
std::vector<char> fileContents;
fileContents.reserve(fileSize);
fileContents.assign(std::istreambuf_iterator<char>(testFile),
                    std::istreambuf_iterator<char>());
Run Code Online (Sandbox Code Playgroud)

  • 是的.如上所述,代码是不正确的,因为`fileContents.begin()`不可解除引用(它等于`fileContents.end()`).具有调试支持的STL实现(如Visual C++ 2010 STL)应该在执行此代码时引发断言. (6认同)
  • @wilhelmtell是这个(第二个选项)比简单地执行`vector <char> fileContents(fileSize);`和`testFile.read(&fileContents [0],fileSize);`?从快速测试(150MB文件)来看,使用read在速度方面看起来效率更高 (3认同)

Max*_*kin 5

如果您想要真正的零拷贝读取,即消除从内核到用户空间的拷贝,只需将文件映射到内存即可。编写您自己的映射文件包装器或使用boost::interprocess.