C++ Grouping repetitions within Vector -


i've got file structured this:

a 123456 0 g 123456 5 235334 0 b 123456 2 

each piece of information being stored so:

temp.code >> temp.personid >> temp.data 

i've stored information in vector

 ifstream fin("test.txt");  vector<testclass> test;  testclass temp;  string line;  while (getline(fin, line)) {//.. test.push_back(temp);} 

a given personid can come numerous times within file. want iterate through vector , group repetitions single class object per personid, goal want sum data each particular object such output file above be:

123456 : 7 235334 : 0 

what elegant way approach this?

thanks

the following code uses std::unordered_map suggested comments already. read file line line.
code assumes person's id of type int, code of type std::string , data of type int.

it inserts every person (here example struct) map. if person's id there sum data. means solution doesn't use temporary std::vector std::unordered_map.

see live example data on ideone.com.

code:

#include <iostream> #include <sstream> #include <fstream> #include <string> #include <unordered_map>  struct person {    std::string code;    int         data; };  typedef std::unordered_map<int, person> personmap;  int main() {    std::ifstream fin("test.txt");     personmap persons;     /* line line reading */    (std::string line; std::getline(fin, line); )    {       std::istringstream iss(line);        int    personid;       person persondata;        /* parse line std::string, int, int */       iss >> persondata.code >> personid >> persondata.data;        /* insert map , save result */       std::pair<personmap::iterator, bool> insertresult =          persons.insert(std::pair<int, person>(personid, persondata));        /* if personid there */       if (!insertresult.second)       {          insertresult.first->second.data += persondata.data;       }    }     /* output whole map */    for(auto const &person : persons)    {       std::cout << person.first << " : " << person.second.data << "\n";    }    std::cout << std::flush; } 

output:

235334 : 0 123456 : 7 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -