4

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

1 回答 1

9

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

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;
}
于 2013-05-18T13:23:44.423 回答