c++ - 从文件读取时提高空间复杂度

标签 c++ readfile space-complexity

我在文件中有一行任意长的整数(或浮点值),用逗号分隔:

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::stringconst char* 的转换)

优化内存利用率的方法有哪些?

谢谢!

最佳答案

是这样的吗?

float val;
while (file >> val)
{
  values[count++] = val;
  char comma;
  file >> comma; // skip comma
}

关于c++ - 从文件读取时提高空间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6892784/

相关文章:

python - 计算结构中的截留水

python - 空间复杂度是多少?

c++ - 从 QAbstractItemModel 返回自定义用户类型

c++ - 使用 boost void 分配器是不好的做法吗?

c++ - 所有 C++ 编译器都生成 C 代码吗?

java - 使用 jarfile 中不可用的 JSONParser 读取 JSON 文件

c# - XAudio2 - 使用动态缓冲区时破解输出

python - 如何使用 read 方法在 Python 中将字符转换为行

c++ - 遇到空格时如何停止阅读一行?

c - 为什么这个函数的空间复杂度是m*n?