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

时间:2015-04-22 16:05:12

标签: c++ scalability

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

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

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

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

有没有更好的方法来执行此操作或C ++标准库的意思?

3 个答案:

答案 0 :(得分:0)

您可以使用 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;

答案 1 :(得分:0)

为什么不只有一个名为sum的变量和一个名为temp的变量。基本概要:

-Recurse

答案 2 :(得分:-1)

伪代码:

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