c++ - implement reverse_iterator for my string class (also rbegin() and rend() methods) -


below code string class. want implement reverse_iterator , rbegin() , rend() methods. have pasted code assign method. string::reverse_iterator rbegin = str2.rbegin(); string::reverse_iterator rend = str2.rend(); for(string::reverse_iterator b = rbegin; b!= rend; ++b) { cout<<*b; }

class string {//my custom string class  public:      class iterator:public std::iterator<std::random_access_iterator_tag, char> {     public:         iterator():ch(null){}         iterator(const iterator& it) : ch(it.ch) {}          char& operator*() { return *ch; }         iterator& operator++() {             ch = ch+1;             return *this;         }         bool operator==(const iterator& rhs) {             return ch == rhs.ch;         }         bool operator!=(const iterator& rhs) {             return ch != rhs.ch;         }      private:         friend class string;         iterator(char* c):ch(c) {}         char* ch;     };     explicit string();     string(const string& str);     string(const char* s);     ~string();     iterator begin();     iterator end(); private:     char* _string;     size_t _length;     size_t _capacity; };  //iterator end string::iterator string::end() {     //return iterator();     if(_length == 0) {         return iterator(_string);     } else {         return iterator(_string+_length+1);     } } void string::assign (const char* str) { if(sizeof(str) >= max_size()) {     throw std::bad_alloc("string size greater max size"); } if(_string != null) {     delete[] _string; } _length = strlen(str); _capacity = _length < 5 ? 5 : _length; _string = new char[_capacity+1]; memset(_string, 0, _capacity+1); memcpy(_string, str, _length); }  int main() {     string str2;     str2.assign("this assigned");     string::iterator begin = str2.begin();     string::iterator end = str2.end();     //below loop should print "this assigned" , working fine     for(string::iterator b = begin; b!= end; ++b) {         cout<<*b;     }      return 1; } 

reverse iterators can implemented in terms of bidirectional iterators:

typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator;  reverse_iterator rbegin() {   return reverse_iterator(end()); }  reverse_iterator rend() {   return reverse_iterator(begin()); } 

... , same const iterators

however, forward iterator implementation needs bidirectional, meaning must support -- operator:

iterator& operator--()  {     --ch;     return *this; } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -