简体   繁体   中英

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

Let's say I have a file containing multiple rows of 3 columns:

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

The goal is to find the sum of each column. The solution is simple: make 3 variables for the sum and then 3 more temp variables.

However, this solution doesn't scale well. What if there are 6 columns? Then I'd have to make a total of 12 variables. There are other ways like making only a count variable and a temp variable and adding the temp variable to the correct sum by using the modulus of the count. But that seems like a hack.

Is there a better way of doing this or a C++ standard library meant for this?

You can use a vector to dynamically adapt to the number of columns. Each element of the vector corresponds to the sum of one column.

You can do this this way:

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

This code is designed for full flexibility: not all the lines need to have the same number of columns (the missing columns are simply considered as 0).

For example with the file:

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

it will display:

14; 23; 28; 23; 28;

Why not just have a single variable called sum and a variable called temp. Basic outline:

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

Pseudocode:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM