plus.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * cxxomfort example: plus
  3. *
  4. * This program provides sample usage of the
  5. * "transparent functor" feature.
  6. *
  7. * The program will take text as input until an end-of-file indicator is sent.
  8. * Text willl then be processed in search of vowels. The aggregation of vowels
  9. * per line is done via std::accumulate using a re-defined operator%
  10. * (itself wrapped via transparent modulus<>).
  11. *
  12. * As an added point, this also tests that
  13. * CXXO_FOREACH is working correctly.
  14. *
  15. */
  16. #include <cxxomfort/cxxomfort.hpp>
  17. // functional
  18. #include <functional>
  19. #include <string>
  20. #include <deque>
  21. #include <sstream>
  22. #include <numeric>
  23. #include <map>
  24. #include <cxxomfort/library/foreach.hpp>
  25. struct Foo {
  26. std::array<unsigned int,5> sarr;
  27. explicit Foo(std::string const& q)
  28. : sarr() {
  29. using namespace std;
  30. if (q.length() >0) {
  31. for (size_t s= 0; s < q.length(); ++s) {
  32. if (false) {}
  33. else if (tolower(q[s] == 'a')) sarr[0]++;
  34. else if (tolower(q[s] == 'e')) sarr[1]++;
  35. else if (tolower(q[s] == 'i')) sarr[2]++;
  36. else if (tolower(q[s] == 'o')) sarr[3]++;
  37. else if (tolower(q[s] == 'u')) sarr[4]++;
  38. } // for
  39. }
  40. }
  41. };
  42. struct FooMap {
  43. typedef std::map<unsigned int, unsigned int> datatype;
  44. typedef datatype::const_iterator datatype_iterator;
  45. datatype map;
  46. };
  47. FooMap operator+ (FooMap const& fm, Foo const& foo);
  48. typedef std::deque<Foo> Container;
  49. int main () {
  50. using namespace std;
  51. Container cont;
  52. string sin;
  53. while ( getline(cin,sin) ) {
  54. cont.push_back( Foo(sin) );
  55. }
  56. FooMap themap;
  57. // this is where the magic happens
  58. themap= accumulate ( begin(cont), end(cont), themap, plus<void>() );
  59. CXXO_FOREACH( FooMap::datatype::value_type const& k, themap.map) {
  60. cout<< (char)(k.first)<< " -> "<< k.second<< endl;
  61. }
  62. }
  63. FooMap operator+ (FooMap const& fm, Foo const& foo) {
  64. FooMap ret(fm);
  65. (ret.map)['a']+= foo.sarr[0];
  66. (ret.map)['e']+= foo.sarr[1];
  67. (ret.map)['i']+= foo.sarr[2];
  68. (ret.map)['o']+= foo.sarr[3];
  69. (ret.map)['u']+= foo.sarr[4];
  70. return ret;
  71. }