adding data from multiple files

I have some data in 10 different files. col1 of each file contains ID. Same ID may be in 2 or more files. Now I have to add the data in all 10 files based on ID.

for example:

file 1

1 0.36
2 0.65
3 0.58
4 0.41

file 2

2 2.56
4 2.45
6 0.36
8 0.69

file 3

2 0.26
6 0.58
7 0.47
5 0.28

now my output should be:

1 0.36
2 3.47
3 0.58
4 2.86
5 0.28
6 0.94
7 0.47
8 0.69

Any suggestion to solve the problem?

I think you can just use a if statement to add the values if ID = X

i've done a bit but need to do some work now soz.

this wont compile as i've not done the readin in of the files, but that's pretty standard stuff.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <vector>



class Id_Info
{
public:
	int m_id;
	double m_sum;

	Id_Info(int id, double number)
		: m_id(id), m_sum(number)
	{

	}

};

bool IdExists(const std::vector<Id_Info>& Ids, const int id)
{
	bool bRtn(false);

	std::vector<Id_Info>::const_iterator it;

	for(it=Ids.begin();it!=Ids.end();it++)
	{
		if(it->m_id == id)
		{
			bRtn = true;
			break;
		}
	}
}


void AddToExisting(const std::vector<Id_Info>& Ids, int idNumber, double number)
{
	//find the id number in the list then add the number to the running total so far
}



int main()
{
	
	std::vector<Id_Info> Ids;

	// iterate over the number of file and read each line.
	// parse both the id and the number after it
	// i'm assuming you can do this, and assign them to the following variables.
	int idNumber; 
	double number;


	if(IdExists(Ids, idNumber))
	{
		AddToExisting(idNumber, number);
	}
	else
	{ 
                // create a new entry in our vector.
		Id_Info inf(Ids, idNumber, number);
		Ids.push_back(inf);
	}


}
Last edited on
You could use a std::map<int, double>
and either add the value to an existing element if found, or insert a new element into the map.

http://www.cplusplus.com/reference/map/map/find/
http://www.cplusplus.com/reference/map/map/insert/
yep, i'd go with Chervil's suggestion. i've just over-complicated things :)
how can I use the 'map'??
by reading the links in Chervil's post.
Topic archived. No new replies allowed.