1

ファイル内にコンマで区切られた任意の長さの整数 (または浮動小数点値) の行があります。

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*)

メモリ使用率を最適化する方法は何ですか?

ありがとう!

4

3 に答える 3

4

このようなもの?

float val;
while (file >> val)
{
  values[count++] = val;
  char comma;
  file >> comma; // skip comma
}
于 2011-07-31T22:39:58.203 に答える
0

scanfを使用するというosgxの提案に基づいて何かを試してみたかった:

freopen("testcases.in", "r", stdin);
while( count < total_values)
       {
         scanf("%f,",&values[count]);
         count++;
       }
于 2011-08-02T19:46:37.950 に答える