从文件中查找多个总和的最有效方法是什么

What is the most efficient way to find multiple sums from a file?

本文关键字:和的 有效 方法 是什么 文件 查找      更新时间:2023-10-16

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

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

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

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

有没有更好的方法来做到这一点,或者有一个C++标准库?

为什么不只有一个叫做 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

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

您可以通过以下方式执行此操作:

#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;

伪代码:

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; }