2013-08-06 59 views
1

假設我在文本文件中有一組1000個統計數據。第一列代表索引號,第二列代表索引號的值。索引可以重複,相應的值可以不同。我想統計每個指標的發生率和各個值的總和。具有類似索引值的總和

我編寫了一個代碼,它給出了索引出現的結果,但它未能給出相應的值總和。

假設我的文本文件有一個像這個 -

#index value 
    4  0.51 
    5  0.13 
    5  0.53 
    5  0.25 
    6  0.16 
    6  0.16 
    7  0.38 
    4  0.11 
    3  0.101 
    4  0.32 
    4  0.2 ... and more 

所以在這個一組數據的區分

指數4 發生 4倍,對應的總和的值=(0.51 + 0.11 + 0.32 + 0.2)= 1.14

同樣

指數5 發生 2次和值的總和=(0.13 + 0.53)= 0.66等

我的代碼

這是我的代碼 -

#include <iostream> 
#include <map> 
#include <fstream> 

using namespace std; 


int main() 
{ 
    map<double,double> index; 
    double number,value; 
    double total; 


    ifstream theFile ("a1.txt"); 
    while(theFile >> number >> value) 
    { 
     ++index[number]; 
     total +=value; 
    } 
    cout<<"index\t occurs\t total"<<endl; 


    for(auto loop = index.begin(); loop != index.end();++loop) 
    { 
     cout << loop->first << "\t " << loop->second << "\t \t "<< total<<endl; 
    } 
    return 0; 
} 

此代碼生成結果-

index occurs total 
3  1  2.851 
4  4  2.851 
5  3  2.851 
6  2  2.851 
7  1  2.851 

雖然發生次數是正確的,但在

總+ =值;

不會生成我正在尋找的輸出。我怎樣才能得到每個指標的總和?

+4

您的總計似乎計算整個文件中的每個條目的總數,而不是每個單獨的索引。以類似的方式,你積累'發生'列,你會想積累'總'列。 –

+0

@ChrisCooper:怎樣才能累積整列?你能幫我用僞代碼嗎? – aries0152

+0

我正在寫一個答案。 –

回答

2

您的總計當前只計算整個文件中的總數,而不是每個索引的總數。以類似的方式積累「發生」列,您可能需要累積「總計」列。看看你的代碼修改如下:

#include <iostream> 
#include <map> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    map<double, double> index; 
    double number, value; 
    map<double, double> total; 

    ifstream theFile ("a1.txt"); 
    while(theFile >> number >> value) 
    { 
     ++index[number]; 
     total[number] += value; 
    } 

    cout << "index\t occurs\t total" << endl; 
    for(auto loop = index.begin(); loop != index.end();++loop) 
    { 
     cout << loop->first << "\t " << loop->second << "\t \t "<< total[loop->first] << endl; 
    } 
    return 0; 
} 

我存儲每個列在自己的總地圖,就像你存儲在自己的地圖索引相同的方式。

0

您要添加到valuetotal指數,而你需要爲每個索引單獨total

將索引映射到與其匹配的值向量的索引將是最簡單的,因此您可以在單獨的步驟中爲每個索引完成總和。

你的閱讀循環的主體可以是這樣的

index[ number ].push_back(value); 

然後在所有指數中的生產在其相關的矢量元素的總和項循環。 (提示 - accumulate是一個常見的名稱....)

編輯:哦,計數顯然是每個向量中的元素數量。

+0

由於OP只對每個索引(和發生次數)的累計總數感興趣,因此不需要爲每個索引分別創建一個向量。簡單的計數和累計總數就足夠了。 – WhozCraig

7
  1. 您需要每個索引total
  2. 您需要每個索引count

這個簡單的解決方法是使用下面的結構:

struct per_index 
{ 
    int count; 
    double total; 
    per_index(): total(0), count(0) {} 
}; 

std::map<int, per_index> index; 

... 

index[number].count++; 
index[number].total += value; 

請注意,我不相信你number您閱讀應該(或需要)爲double,它只是使生活更加複雜,因爲double在比較平等方面存在困難。所以我去了number是一個int - 你需要改變你的代碼中的聲明。