fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <map>
  5. #include <sstream>
  6.  
  7. struct Counter
  8. {
  9. std::map<std::string, int> wordCount;
  10. void operator()(const std::string & item) { ++wordCount[item]; }
  11. operator std::map<std::string, int>() { return wordCount; }
  12. };
  13.  
  14.  
  15. int main()
  16. {
  17. std::string input =
  18. "Relations between data in the STL are represented with maps."
  19. "A map is a directed relation, by using it you are representing "
  20. "a mapping. In this directed relation, the first type is related to "
  21. "the second type but it is not true that the inverse relationship "
  22. "holds. This is useful in a lot of situations, but there are some "
  23. "relationships that are bidirectional by nature.";
  24.  
  25. std::istringstream instream (input);
  26.  
  27. std::istream_iterator<std::string> start(instream);
  28. std::istream_iterator<std::string> end;
  29.  
  30. std::map<std::string, int> wordCount = std::for_each(start, end, Counter());
  31.  
  32. for (std::map<std::string, int>::iterator it = wordCount.begin(); it != wordCount.end(); ++it)
  33. {
  34. std::cout << it->first <<" : "<< it->second << std::endl;
  35. }
  36. }
Success #stdin #stdout 0s 2864KB
stdin
Standard input is empty
stdout
In : 1
Relations : 1
STL : 1
This : 1
a : 3
are : 4
between : 1
bidirectional : 1
but : 2
by : 2
data : 1
directed : 2
first : 1
holds. : 1
in : 2
inverse : 1
is : 4
it : 2
lot : 1
map : 1
mapping. : 1
maps.A : 1
nature. : 1
not : 1
of : 1
related : 1
relation, : 2
relationship : 1
relationships : 1
represented : 1
representing : 1
second : 1
situations, : 1
some : 1
that : 2
the : 4
there : 1
this : 1
to : 1
true : 1
type : 2
useful : 1
using : 1
with : 1
you : 1