fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5. #include <algorithm>
  6.  
  7. // who likes typing
  8. typedef std::vector<std::string> MyVector;
  9. typedef std::map<std::string, unsigned int> MyMap;
  10.  
  11. class MapCount
  12. {
  13. private:
  14. MyMap& theMap;
  15.  
  16. public:
  17. MapCount(MyMap& arg) : theMap(arg) { }
  18.  
  19. // used by for_each
  20. void operator ()(const std::string& s) { ++theMap[s]; }
  21. };
  22.  
  23. int main()
  24. {
  25. MyVector myVector = { "foo","foo","bar","roo","foo","bar" };
  26.  
  27. MyMap mymap;
  28. std::for_each(myVector.begin(), myVector.end(), MapCount(mymap));
  29.  
  30. for (MyMap::const_iterator it = mymap.begin(); it != mymap.end(); ++it)
  31. std::cout << it->first << '\t' << it->second << std::endl;
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
bar	2
foo	3
roo	1