Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Below is code for my String class. I want to implement reverse_iterator and rbegin() and rend() methods. Have pasted code for 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 to 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 is greater than 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 is assigned");
    String::iterator begin = str2.begin();
    String::iterator end = str2.end();
    //below loop should print "This is assigned" and is working fine
    for (String::iterator b = begin; b != end; ++b) {
        cout << *b;
    }

    return 1;
}
like image 431
user2396831 Avatar asked Jan 13 '23 08:01

user2396831


1 Answers

Reverse iterators can be 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());
}

... and then the same for const iterators

However, your forward iterator implementation needs to be bidirectional, meaning that it must also support the -- operator:

iterator& operator--() 
{
    --ch;
    return *this;
}
like image 123
Charles Salvia Avatar answered Jan 15 '23 22:01

Charles Salvia