fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <cctype>
  4. #include <algorithm>
  5. #include <iterator>
  6.  
  7. template <typename InputIterator>
  8. class IteratorWithSkip : public std::iterator<std::forward_iterator_tag, typename InputIterator::value_type>
  9. {
  10. public:
  11. typedef typename InputIterator::value_type value_type;
  12. typedef bool (*skip_function)(value_type);
  13.  
  14. explicit IteratorWithSkip(InputIterator begin, InputIterator end, skip_function f)
  15. : m_final(false), m_it(begin), m_end(end), m_f(f) {}
  16.  
  17. IteratorWithSkip() : m_final(true) {}
  18.  
  19. IteratorWithSkip(const IteratorWithSkip& it) : m_it(it.m_it), m_end(it.m_end), m_final(it.m_final), m_f(it.m_f) {
  20. skip();
  21. }
  22.  
  23. IteratorWithSkip& operator=(const IteratorWithSkip& it) {
  24. if (this != &it) {
  25. m_it = it.m_it;
  26. m_end = it.m_end;
  27. m_final = it.m_final;
  28. m_f = it.m_f;
  29. }
  30. return *this;
  31. }
  32.  
  33. IteratorWithSkip operator++(int) {
  34. IteratorWithSkip tmp(m_it, m_end, m_f);
  35. ++(*this);
  36. return tmp;
  37. }
  38.  
  39. IteratorWithSkip& operator++(){
  40. if (m_it != m_end) ++m_it;
  41. skip();
  42. return *this;
  43. }
  44.  
  45. bool operator==(const IteratorWithSkip& it) const {
  46. return (it.m_final && m_it == m_end);
  47. }
  48.  
  49. bool operator!=(const IteratorWithSkip& it) const {
  50. return ! (*this == it);
  51. }
  52.  
  53. value_type operator*() {
  54. return *m_it;
  55. }
  56. private:
  57. void skip() {
  58. while (m_it != m_end && m_f(*m_it)) ++m_it;
  59. }
  60. bool m_final;
  61. InputIterator m_it, m_end;
  62. skip_function m_f;
  63. };
  64.  
  65. bool is_space (char s)
  66. {
  67. return isspace(s);
  68. }
  69.  
  70. int main()
  71. {
  72. std::string s1 = "hello world", s2 = " hellow o r l d ";
  73. typedef IteratorWithSkip<std::string::iterator> SkipIterator;
  74.  
  75. SkipIterator i1(s1.begin(), s1.end(), is_space), i1_end, i2(s2.begin(), s2.end(), is_space);
  76.  
  77. std::copy (SkipIterator(s2.begin(), s2.end(), is_space),
  78. SkipIterator(),
  79. std::ostream_iterator<char>(std::cout));
  80.  
  81. std::cout << std::endl;
  82.  
  83. std::cout << std::boolalpha << std::equal (i1, i1_end, i2) << std::endl;
  84. }
Success #stdin #stdout 0.02s 2860KB
stdin
Standard input is empty
stdout
helloworld
true