### 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):

 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 #include #include #include #include #include int main () { std::map< int, std::vector > 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.