fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <sstream>
  6.  
  7. using namespace std;
  8.  
  9. struct entry {
  10. string name;
  11. unsigned quantity;
  12. };
  13.  
  14. vector<entry> readData()
  15. {
  16. vector<entry> data;
  17.  
  18. string line, name;
  19. unsigned quantity;
  20.  
  21. while (getline(cin, line) && istringstream(line) >> name >> quantity)
  22. data.push_back({name,quantity});
  23.  
  24. return data;
  25. }
  26.  
  27. void consolidate(vector<entry>& data)
  28. {
  29. auto f = data.begin(), l = data.end();
  30. while (f!=l)
  31. {
  32. auto match = find_if(begin(data), f, [&](entry const& a) { return a.name == f->name; });
  33. if (match != f)
  34. {
  35. match->quantity += f->quantity;
  36. f = data.erase(f);
  37. l = data.end();
  38. } else
  39. {
  40. f++;
  41. }
  42. }
  43. }
  44.  
  45. int main()
  46. {
  47. vector<entry> data = readData();
  48.  
  49. consolidate(data);
  50.  
  51. for (auto it = data.begin(); it != data.end(); ++it)
  52. cout << it->name << " " << it->quantity << "\n";
  53. }
  54.  
Success #stdin #stdout 0s 3484KB
stdin
apple 5
pear 2
grape 6
mangoes 3
apple 2
mangoes 9
stdout
apple 7
pear 2
grape 6
mangoes 12