为了提高从文件读取的性能,我试图将大(几MB)文件的整个内容读入内存,然后使用istringstream来访问信息.
我的问题是,哪个是读取此信息并将其"导入"到字符串流中的最佳方法?这种方法的一个问题(参见下文)是在创建字符串流时,缓冲区被复制,内存使用量增加一倍.
#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream is;
is.open (sFilename.c_str(), ios::binary );
// get length of file:
is.seekg (0, std::ios::end);
long length = is.tellg();
is.seekg (0, std::ios::beg);
// allocate memory:
char *buffer = new char [length];
// read data as a block:
is.read (buffer,length);
// create string stream of memory contents
// NOTE: this ends up copying the buffer!!!
istringstream iss( string( buffer ) );
// delete temporary buffer
delete [] buffer;
// close …Run Code Online (Sandbox Code Playgroud) 是否存在规范/公共/免费实现变体,std::stringstream每次调用时我都不会为完整的字符串副本付费str()?(可能通过c_str()在骨科中提供直接成员?)
我在这里发现了两个问题:
并且"当然"不推荐使用的std::strstream类确实允许直接缓冲区访问,尽管它的界面非常古怪(除了它被弃用).
似乎人们可以找到几个代码示例来解释如何自定义std::streambuf以允许直接访问缓冲区 - 我没有在实践中尝试过,但它似乎很容易实现.
我的问题实际上是两个方面:
std::[o]stringstream(或者更确切地说,basic_stringbuf)不允许直接缓冲区访问,而只能通过整个缓冲区的(昂贵)副本进行访问?注意:副本的性能损失str()是非常可测量的(*),因此当我到目前为止看到的用例实际上从不需要从stringstream返回的副本时,必须为此付费似乎很奇怪.(如果我需要副本,我总是可以在"客户端"进行.)
(*):使用我们的平台(VS 2005),我在发布版本中测量的结果是:
// tested in a tight loop:
// variant stream: run time : 100%
std::stringstream msg;
msg << "Error " << GetDetailedErrorMsg() << " …Run Code Online (Sandbox Code Playgroud)