将文件读入std :: vector的有效方式< char&gt ;? [英] Efficient way of reading a file into an std::vector<char>?

查看:182
本文介绍了将文件读入std :: vector的有效方式< char&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想避免不必要的副本。我的目标是沿着以下线:

I'd like to avoid unnecessary copies. I'm aiming for something along the lines of:

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

(不起作用,因为 reserve 实际上没有插入任何东西到矢量,所以我不能访问 [0] )。

(which doesn't work because reserve doesn't actually insert anything into the vector, so I can't access [0]).

课程, std :: vector< char> fileContents(fileSize)可以工作,但是有一个初始化所有元素( fileSize 可能相当大)的开销。同样的 resize()

Of course, std::vector<char> fileContents(fileSize) works, but there is an overhead of initializing all elements (fileSize can be rather big). Same for resize().

这个问题不是那么重要的开销是多少。

This question is not so much about how important that overhead would be. Rather, I'm just curious to know if there's another way.

推荐答案

规范形式是这样的:

#include<iterator>
// ...

std::ifstream testFile("testfile", std::ios::binary);
std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)),
                               std::istreambuf_iterator<char>());

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

If you are worried about reallocations then reserve space in the vector:

#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>());

这篇关于将文件读入std :: vector的有效方式&lt; char&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆