2015-04-22 66 views
1

比方說,我有一個包含3列的多行文件:從文件中查找多個總和的最有效方法是什麼?

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

的目標是找到每個列的總和。解決方案很簡單:爲總和製作3個變量,然後製作3個更多的臨時變量。

但是,此解決方案不能很好地擴展。如果有6列?然後,我必須總共創建12個變量。還有其他一些方法,比如只做一個計數變量和一個臨時變量,並通過使用計數模數將臨時變量添加到正確的總和中。但是,這似乎是一個黑客。

有沒有更好的方式來做到這一點或C++標準庫的意思呢?

+7

使用'vector'。 –

+0

如果你使用一個隊列,每一行你從頭開始,然後繼續直到'\ n'字符,然後將指針移回頭部。然後當你做完所有事情時,只需走一次隊列就可以得到輸出。比矢量imo更少的開銷。 – Fallenreaper

+0

@CoryNelson你可以闡述一下使用矢量嗎? – joshualan

回答

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

在C++中使用隊列是一個不錯的主意...... – Caduchon

+0

哦,好的。我不確定。我認爲你可以在流中讀取以優化它,但我認爲它會工作得很好。我的意思是,至少對我來說是有意義的。會更喜歡爲什麼我的不是一個好主意。 – Fallenreaper

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

爲什麼不只是一個單一的變量稱爲總和與所謂的氣溫變化。基本概述:

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 
+0

這個解決方案只需要大約3個變量來完成工作,並且可擴展到所有尺寸的輸入,甚至可以改變每行數值的輸入! –

相關問題