具有相似索引的值的总和

  • 本文关键字:索引 相似 c++ c++11 io
  • 更新时间 :
  • 英文 :


假设我在一个文本文件中有一组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<<"indext occurst 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

虽然出现的次数是正确的,但

合计+=数值;

不会生成我想要的输出。如何获得每个索引的总和?

  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——您需要更改代码中的声明。

您的合计当前只计算整个文件中的合计,而不是每个索引的合计。与累积"occurs"列的方式类似,您希望累积"total"列。请参阅下面修改的代码:

#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 << "indext occurst 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;
}

我将每一列存储在其自己的总映射中,就像将索引存储在其自身的映射中一样。

您为每个索引添加valuetotal,而为每个索引需要单独的total

将索引映射到与之匹配的值向量将是最简单的,因此您可以在单独的步骤中对每个索引求和。

你的阅读循环的主体可以是类似的东西

index[ number ].push_back( value );

然后循环索引中的所有条目,生成其关联向量中元素的总和。(提示-accumulate是一个通用名称……)

编辑:哦,计数显然是每个向量中元素的数量。

最新更新