为我的字符串类(也是rbegin()和rend()方法实现reverse_iterator)

时间:2013-05-18 13:14:57

标签: c++ iterator stdstring reverse-iterator

下面是我的String类的代码。我想实现reverse_iterator和rbegin()以及rend()方法。 已粘贴了assign方法的代码。     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;
}

1 个答案:

答案 0 :(得分:3)

反向迭代器可以用双向迭代器实现:

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());
}

...然后对const迭代器

进行相同的操作

但是,您的前向迭代器实现需要是双向的,这意味着它还必须支持--运算符:

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