具有相似索引的值的总和

ari*_*152 1 c++ io c++11

假设我在一个文本文件中有一组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
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下 -

指数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;
}
Run Code Online (Sandbox Code Playgroud)

此代码生成结果 -

index  occurs  total
3       1     2.851
4       4     2.851
5       3     2.851
6       2     2.851
7       1     2.851
Run Code Online (Sandbox Code Playgroud)

虽然发生的次数是正确的,但是

总+ =价值;

不会生成我正在寻找的输出.如何获得每个索引的总和?

Mat*_*son 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;
Run Code Online (Sandbox Code Playgroud)

请注意,我不相信你number所读的应该(或需要)是一个double,它只会使生活变得更复杂,因为double在比较平等方面存在困难.所以我已经number成为了int- 你需要更改代码中的声明.