首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >提高读取文件时的空间复杂性

提高读取文件时的空间复杂性
EN

Stack Overflow用户
提问于 2011-07-31 22:34:37
回答 3查看 302关注 0票数 1

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

代码语言:javascript
复制
1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,9,3,...  (can go upto >100 MB)

现在,我必须读取这些值并将它们存储在一个数组中。

我目前的实现如下:

代码语言:javascript
复制
 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*的转换)

优化内存利用率的方法是什么?

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-07-31 22:39:58

像这样吗?

代码语言:javascript
复制
float val;
while (file >> val)
{
  values[count++] = val;
  char comma;
  file >> comma; // skip comma
}
票数 4
EN

Stack Overflow用户

发布于 2011-08-01 00:26:54

使用boost令牌器istreambuf_iterator

代码语言:javascript
复制
std::vector<float> test; //Optionally call reserve to avoid frequent memory reallocation
boost::tokenizer<boost::char_separator<char>, std::istreambuf_iterator<char> > tokens(std::istreambuf_iterator<char> (in), std::istreambuf_iterator<char>(), boost::char_separator<char>(","));
//Replace this lambda by your favourite conversion function.
std::transform(tokens.begin(), tokens.end(), std::back_inserter(test), [](std::basic_string<char> s) { return atof(s.c_str()); } );

编辑:test是我为values使用的,只是它是一个std::vector而不是数组,这通常是更好的选择。

Imho,这个代码有一些优点。迭代器有内置的eof处理,您可以很容易地展开分隔符。这是非常容易出错的(特别是当您使用一个使用异常的atof替换时)。

票数 1
EN

Stack Overflow用户

发布于 2011-08-02 19:46:37

我想尝试一些基于osgx关于使用scanf的建议的东西:

代码语言:javascript
复制
freopen("testcases.in", "r", stdin);
while( count < total_values)
       {
         scanf("%f,",&values[count]);
         count++;
       }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6892784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档