下面是我的 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;
}