我有一种情况,我需要处理大量(许多GB)的数据量:
每次迭代中的数据都是独立的.
我的问题是,我想最小化(如果可能消除)堆分配的内存使用量,因为它目前是我最大的性能问题.
有没有办法将C字符串(char*)转换为stl C++字符串(std :: string),而不需要std :: string来内部分配/复制数据?
或者,我可以使用stringstreams或类似的东西来重用大缓冲区吗?
编辑:感谢您的回答,为清楚起见,我认为修改后的问题将是:
如何有效地构建(通过多个附加)一个stl C++字符串.如果在循环中执行此操作,其中每个循环完全独立,我如何重新使用此分配的空间.
如何从fstream到字符串对象中准确读取128个字节?
我写了一些代码来读取文件的前128个字节并打印它然后打印文件的最后128个字节并打印出来.最后一部分可以工作,因为您可以轻松地迭代到EOF,但是如何从前面获得正好128个字节?下面的代码不起作用,因为你不能添加128到ifstream的迭代器,它不是可转位,仅可递增的(似乎).
当然我可以制作一个迭代器和*++它128次,但必须有一条直线的方法来做,对吧?
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char **argv)
{
std::ifstream ifs ("input.txt",std::ifstream::in | std::ifstream::binary);
if (ifs.good())
{
// read first 128 bytes into a string
ifs.seekg(0,std::ifstream::beg);
std::string first128((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>(ifs))+128);
std::cout << first128 << std::endl;
// read last 128 bytes into a string
ifs.seekg(-128,std::ifstream::end);
std::string last128((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
std::cout << last128 << std::endl;
return 0;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud) 我的桌面上有 .txt 文件。我需要将所有字节从内存读取到数组。
我尝试将文本从文件读取到字符串,然后使用 memcpy() 从字符串读取字节,但我认为这是不正确的。
Tnx。
ifstream File("C:\\Users\\Flone\\Desktop\\ass.txt");
string file_text;
//start to read TEXT file (look end below):
char word_buffer[30];
for (int i = 0; i < 30; i++)
{
word_buffer[i] = NULL;
}
while (File.eof() == false)
{
File >> word_buffer;
for (int i = 0; i < 30; i++)
{
if (word_buffer[i] != NULL)
{
file_text += word_buffer[i];
}
}
if (File.eof()==false) file_text += " ";
for (int i = 0; i < 30; i++)
{
word_buffer[i] …Run Code Online (Sandbox Code Playgroud)