Massive Array

Hi there. I have a massive Array, which gets outputted to a .txt file.

It looks a bit like this: there are are set of numbers ranging from 1-9 and then beside each of those numbers there are a larger set of numbers, so for 1 there might 1:2, 1:7, 1:9 etc. then it goes to 2:1, 2:5. 2:11 etc.

e.g.

1 2
1 7
1 9
2 1
2 5
2 11

How can I add up all the values of 1's and all the values of 2's, without calculating the entire size of the Array?

So 1 = 18
2 = 17

Thanks for the help.

Last edited on
What do you mean "without calculating the entire size of the array"? In order to add all the numbers together, you will need to traverse the entire array.

As a first hint, you'll probably want a way to sum each value as you reach it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
#include <map>
using namespace std;

int main()
{
   int num, freq;
   map<int,int> M;

   ifstream in( "data.txt" );
   while( in >> num >> freq ) M[num] += freq;

   for ( auto e : M ) cout << e.first << ": " << e.second << '\n';
}
1: 18
2: 17

As LastChance's elegant solution shows, you took a conceptual detour that prevented you from seeing the easy solution:
I have a massive Array
.

When looking at a problem, it's important to consider the problem as stated and not to classify it as something else too quickly. In this case you have pairs of numbers and you prematurely classified it as a 2D array.
Topic archived. No new replies allowed.