fork download
  1. #include <utility>
  2. #include <set>
  3. #include <iostream>
  4. #include <algorithm>
  5.  
  6. template<class T>
  7. class CompareWords {
  8. public:
  9. bool operator()(T s1, T s2)
  10. {
  11. if (s1.length() == s2.length())
  12. {
  13. return ( s1 < s2 );
  14. }
  15. else return ( s1.length() < s2.length() );
  16. }
  17. };
  18.  
  19. template<class Iterator, class Clumps, class Compare>
  20. void reduce_clumps( Iterator begin, Iterator end, Clumps&& clumps, Compare&& compare) {
  21. if (begin==end) return;
  22. typedef decltype(*begin) value_type;
  23. std::size_t count = 1;
  24. Iterator run_end = std::find_if( std::next(begin), end, [&]( value_type v ){
  25. if (!compare(*begin, v)) {
  26. ++count;
  27. return false;
  28. }
  29. return true;
  30. });
  31. clumps( begin, run_end, count );
  32. return reduce_clumps( std::move(run_end), std::move(end), std::forward<Clumps>(clumps), std::forward<Compare>(compare) );
  33. }
  34.  
  35. int main() {
  36. typedef std::multiset<std::string> mySet;
  37. typedef std::multiset<std::string>::iterator mySetItr;
  38.  
  39. mySet mWords { "A", "A", "B" };
  40.  
  41. reduce_clumps( mWords.begin(), mWords.end(),
  42. []( mySetItr run_start, mySetItr run_end, std::size_t count )
  43. {
  44. std::cout << "Word \"" << *run_start << "\" occurs " << count << " times\n";
  45. },
  46. CompareWords<std::string>{}
  47. );
  48. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Word "A" occurs 2 times
Word "B" occurs 1 times