Sum of a column

I have a txt file with data of each day store in columns. number of the year is in first column. Now I need the total data of each year for each column data. my data structure is like this.

yyyy 12 1 15 16 20
2001 0.125 0.15 0.25 0.23 0.25
2001 0.25 0.14 0.3 0.25 0.69
2002 0.36 0.45 0.26 0.36 0.33
2002 0.36 0.25 0.25 0.2 0.25

Row 1 is the number of each daily dataset. I want to store the sum in the following format,

yyyy 12 1 15 16 20
2001 0.150 0.29 0.28 0.48 0.94
2002 0.72 0.70 0.51 0.56 0.58

Something like this (error handling is elided):

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
#include <map>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>

int main ()
{
    std::map< int, std::vector<double> > map ;

    std::istringstream file
    {
        "yyyy 12 1 15 16 20\n"
        "2001 0.125 0.15 0.25 0.23 0.25\n"
        "2001 0.25 0.14 0.3 0.25 0.69\n"
        "2002 0.36 0.45 0.26 0.36 0.33\n"
        "2002 0.36 0.25 0.25 0.2 0.25\n"
    };

    std::string line ;

    // read the first line and determine the number of cols
    std::getline( file, line ) ;

    std::size_t ncols = 0 ;
    {
        std::istringstream stm( line.substr(4) ) ; // skip the "yyyy"
        int i ;
        while( stm >> i ) ++ncols ;
    }

    // for every line that follows
    while( std::getline( file, line ) )
    {
        std::istringstream stm(line) ;
        int year ;
        stm >> year ;
        map[year].resize(ncols) ;
        double value ;
        for( double& v : map[year] ) if( stm >> value ) v += value ;
    }

    // print it out to check
    std::cout << std::fixed << std::setprecision(3) ;
    for( const auto& p : map )
    {
        std::cout << p.first << "  [ " ;
        for( double value : p.second ) std::cout << std::setw(5) << value << ' ' ;
        std::cout << "]\n" ;
    }
}

http://coliru.stacked-crooked.com/a/116aff1375bc7758
Last edited on
I think we need to initialize 'v' at line 40.
Topic archived. No new replies allowed.