Associating values in arrays

I have a data file that looks like the following:

1
2
3
4
5
6
7
8
9
10
11
1  35
4  55
3  20
21 125
12 33
7  4
22 355
4  3
1  32
21 556
25 33


I'm trying to write a program that will associate the first column of numbers with the second column of numbers so I can easily sum the numbers in the second column.

As an example, 1 in the first column occurs twice, and I would need to add the values in the second column associated with the number 1, 35 + 32 = 67 for 1. There is 25 numbers in the first column.

I have this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

const int TYPES = 25;

ifstream infile;
ofstream outfile;

void read(int numbers[])
{
    int sum = 0, i = 0;

    infile.open("data.txt");

    if (!infile)
    {
        cout << "Failed to open data file!";
        cin.get();
        exit(0);
    }

    infile >> numbers[0];

    while (infile)
    {
        infile >> sum;
        infile >> numbers[i];

        i++;
    }
}

int main()
{
    int numbers[TYPES];

    read(numbers);

    cin.get();
    return 0;
}


I've done something like this in perl before using hashes to associate keys with other data, but I'm not sure if c++ has this. Do I need to use a two-dimensional array for this? Thank you if you can help with this.
You're looking for something like:

1
2
3
4
5
6
7
vector<pair<unsigned, unsigned> > array;

 pair<unsigned, unsigned> element;
 element.first = // first value
 element.second = // second value
 array.push_back(element);

C++ has standard container std::map.
Topic archived. No new replies allowed.