相关疑难解决方法(0)

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

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

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().

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

c++ stl vector

36
推荐指数
2
解决办法
3万
查看次数

标签 统计

c++ ×1

stl ×1

vector ×1