gpt4 book ai didi

c++ - 为我的字符串类实现 reverse_iterator(还有 rbegin() 和 rend() 方法)

转载 作者:行者123 更新时间:2023-11-27 23:15:28 27 4
gpt4 key购买 nike

下面是我的 String 类的代码。我想实现 reverse_iteratorrbegin()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;
}

最佳答案

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

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

关于c++ - 为我的字符串类实现 reverse_iterator(还有 rbegin() 和 rend() 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16624654/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com