to find average for each integer


I have two columns in a txt file. Both columns have integer values. column1 contains ID and column2 contains ratings.
I want to find average ratings for each ID. But I am not able to solve that. How do I solve this?
Last edited on
Can you give us more detail about the data in your file, and what you want to do with it? Your question is so vague, it's hard to know what you're really asking for.
1
2
3
4
5
int col_id,
     col_rating;
std::string line;//line you read from file

sscanf(line.c_str(), "%n %n ", &col_id,&col_rating);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct stats{
   double sum = 0;
   int n = 0;
   double average() const{
      return sum/n;
   }
};

//create a dictionary id->stats
std::map<int, stats> dictionary;
while(input >> id >> rating){
   dictionary[id].sum += rating;
   ++dictionary[id].n;
}
//now may traverse the dictionary an obtain the average
for(auto &x: dictionary)
   std::cout << x.first /*id*/ << x.second.average() << '\n';
Topic archived. No new replies allowed.