假设您想从大型文本文件(~300mb)读取数据到向量数组:(vector<string> *Data
假设列数已知)。
//file is opened with ifstream; initial value of s is set up, etc...
Data = new vector<string>[col];
string u;
int i = 0;
do
{
istringstream iLine = istringstream(s);
i=0;
while(iLine >> u)
{
Data[i].push_back(u);
i++;
}
}
while(getline(file, s));
此代码适用于小文件(<50mb),但读取大文件时内存使用量呈指数增长。我很确定问题在于istringstream
每次循环创建对象。但是,istringstream iLine;
在两个循环之外定义并将每个字符串放入流中iLine.str(s);
并在内部 while-loop ( ) 之后清除流iLine.str(""); iLine.clear();
也会导致相同的内存爆炸顺序。出现的问题:
- 为什么
istringstream
会这样; - 如果是预期行为,如何完成上述任务?
谢谢
编辑:关于第一个答案,我稍后在代码中清理了数组分配的内存:
for(long i=0;i<col;i++)
Data[i].clear();
delete []Data;
完整的编译就绪代码(添加标题):
int _tmain(int argc, _TCHAR* argv[])
{
ofstream testfile;
testfile.open("testdata.txt");
srand(time(NULL));
for(int i = 1; i<1000000; i++)
{
for(int j=1; j<100; j++)
{
testfile << rand()%100 << " ";
}
testfile << endl;
}
testfile.close();
vector<string> *Data;
clock_t begin = clock();
ifstream file("testdata.txt");
string s;
getline(file,s);
istringstream iss = istringstream(s);
string nums;
int col=0;
while(iss >> nums)
{
col++;
}
cout << "Columns #: " << col << endl;
Data = new vector<string>[col];
string u;
int i = 0;
do
{
istringstream iLine = istringstream(s);
i=0;
while(iLine >> u)
{
Data[i].push_back(u);
i++;
}
}
while(getline(file, s));
cout << "Rows #: " << Data[0].size() << endl;
for(long i=0;i<col;i++)
Data[i].clear();
delete []Data;
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << elapsed_secs << endl;
getchar();
return 0;
}