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) &&
  22. istringstream(line) >> name >> quantity)
  23. {
  24. auto found = find_if(begin(data), end(data), [&](entry const& a) { return a.name == name; });
  25. if (end(data) == found)
  26. data.push_back({name, quantity});
  27. else
  28. found->quantity += quantity;
  29. }
  30. return data;
  31. }
  32.  
  33. int main()
  34. {
  35. vector<entry> const data = readData();
  36. for (auto it = data.begin(); it != data.end(); ++it)
  37. cout << it->name << " " << it->quantity << "\n";
  38. }
  39.  
  40.  
Success #stdin #stdout 0s 3480KB
stdin
apple 5
pear 2
grape 6
mangoes 3
apple 2
mangoes 9
stdout
apple 7
pear 2
grape 6
mangoes 12