我在文件中有一行任意长的整数(或浮点值),用逗号分隔:
1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,9,3,... (can go upto >100 MB)
现在,我必须读取这些值并将它们存储在一个数组中。
我目前的实现是这样的:
float* read_line(int dimension)
{
float *values = new float[dimension*dimension]; // a line will have dimension^2 values
std::string line;
char *token = NULL, *buffer = NULL, *tmp = NULL;
int count = 0;
getline(file, line);
buffer = new char[line.length() + 1];
strcpy(buffer, line.c_str());
for( token = strtok(buffer, ","); token != NULL; token = strtok(NULL, ","), count++ )
{
values[count] = strtod(token, &tmp);
}
delete buffer;
return values;
}
我不喜欢这个实现,因为:
- 使用
ifstream
将整个文件加载到内存中,并且 然后被克隆成一个float []
- 没有不必要的重复(从
std::string
到const char*
的转换)
优化内存利用率的方法有哪些?
谢谢!
最佳答案
是这样的吗?
float val;
while (file >> val)
{
values[count++] = val;
char comma;
file >> comma; // skip comma
}
关于c++ - 从文件读取时提高空间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6892784/