C++: looping over a string - iterator? -


let assume have different functions accessing single string str (getting single character of it) , want loop through string every access...how achieve this?

for example:

string str = "abc"; function1(); // returns "a" function2(); // returns "b" function3(); // returns "c" function4(); // returns "a" again function2(); // returns "b" again ... 

so have different functions accessing string str , need kind of iterator gets first character of str if end of str reached.

if want use iterator instead of indexing, use cyclic_iterator, this:

#ifndef cyclic_iterator_h_inc_ #define cyclic_iterator_h_inc_ #include <iterator>  template <class fwdit> class cyclic_iterator_t : public std::iterator<std::input_iterator_tag, typename fwdit::value_type> {     fwdit begin;     fwdit end;     fwdit current; public:     cyclic_iterator_t(fwdit begin, fwdit end) : begin(begin), end(end), current(begin) {}      cyclic_iterator_t operator++() {          if (++current == end)              current = begin;          return *this;      }     typename fwdit::value_type operator *() const { return *current; } };  template <class container> cyclic_iterator_t<typename container::iterator> cyclic_iterator(container &c) {      return cyclic_iterator_t<typename container::iterator>(c.begin(), c.end()); }  #endif 

this quite minimal iterators go--for example, supports pre-increment, not post-increment (and it's forward iterator, can iterator increment , dereference it).

nonetheless, job envision, seems adequate.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -