【问题标题】:What is the most efficient way to find multiple sums from a file?从文件中查找多个总和的最有效方法是什么?
【发布时间】:2015-04-22 16:05:12
【问题描述】:

假设我有一个包含多行 3 列的文件:

3 1 3
1 2 3
4 5 6
. . .

目标是求每列的总和。解决方案很简单:为总和创建 3 个变量,然后再创建 3 个临时变量。

但是,此解决方案不能很好地扩展。如果有 6 列呢?然后我必须制作总共 12 个变量。还有其他方法,例如只制作一个计数变量和一个临时变量,并通过使用计数的模数将临时变量添加到正确的总和中。但这似乎是一个 hack。

有没有更好的方法或为此目的的 C++ 标准库?

【问题讨论】:

  • 使用vector
  • 如果您使用队列,则每行都从头部开始,然后步进到\n 字符,然后将指针移回头部。然后,当您完成所有操作后,只需排队一次即可获得输出。比向量 imo 的开销更少。
  • @CoryNelson 你能解释一下使用向量吗?
  • @joshualan 对 pairsstructs 求和,其中包含您读入的每一列的总和和临时变量。或两个单独的 vectors,一个用于总和和一个用于临时变量。

标签: c++ scalability


【解决方案1】:

为什么不只使用一个名为 sum 的变量和一个名为 temp 的变量。基本大纲:

Initialize sum to 0;
while there are more lines:
    Read 1 line of input till \n is found
        While line has more inputs:
            read each number out of it (using temp) 
            sum += temp
        Next Number
        print out sum and reset it to 0
    Next Line

【讨论】:

  • 这个解决方案只需要大约 3 个变量来完成这项工作,并且可以扩展到所有大小的输入,甚至是改变每行值数量的输入!
【解决方案2】:

您可以使用 vector 来动态适应列数。向量的每个元素对应于一列的总和。

你可以这样做:

#include <iostream>   
#include <string>      // for using getline()
#include <fstream>     // for file reading 
#include <sstream>     // for line parsing with stringstream 
#include <vector>      // for vectors
#include <algorithm>   // for the output trick

using namespace std; 

int main()
{
   vector<int> sum;              // intiial size is 0
   ifstream ifs("test.txt");
   string line; 

   while (getline(ifs, line)) {  // read file line by line; 
     stringstream ss(line);    // and parse each line
     int input; 
     for (int i = 0; ss >> input; i++) {   // read columns (i counts them)
        if (i >= sum.size())       // if there is a new column 
            sum.resize(i+1);              // resize the vector
        sum[i]+=input;             // in any case update sum of the column  
     }
   }                
       // when it's finished, just output the result
   copy(sum.begin(), sum.end(), ostream_iterator<int>(cout, "; ")); 
   cout << endl; 
}

此代码旨在实现完全的灵活性:并非所有行都需要具有相同数量的列(缺少的列被简单地视为 0)。

以文件为例:

3 5 9 10
2 9 8
7 5 6 7 20
2 4 5 6 8

它会显示:

14; 23; 28; 23; 28;

【讨论】:

    【解决方案3】:

    伪代码:

    Open FilePointer (readonly)
    create a queue of ints.
    create a ptr to queue.
    read in a row.
    tokenize on space
    walk array and push onto ptr the value = value + variable
    shift ptr,     ptr = ptr->next()
    at end of row, shift ptr back to head.
    do while not EOF.
    
    walk queue last time, outputing the values.
    while(ptr != nullptr) {  cout << ptr->value; }
    

    【讨论】:

    • 哦,好的。我不确定。我在想你可以在流中阅读以优化它,但我认为它会工作得很好。我的意思是,至少对我来说是有意义的。我会更喜欢为什么我的不是一个好主意。
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2011-10-22
    • 2016-11-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多