在自定义迭代器中定义const_iterator,并使其能够转换为const_iterator,例如:
class MyIterator {
public:
using value_type = int;
using difference_type = long;
using pointer = int*;
using reference = int&;
using iterator_category = std::forward_iterator_tag;
MyIterator(int* ptr) : ptr_(ptr) {}
int& operator*() const {
return *ptr_;
}
MyIterator& operator++() {
++ptr_;
return *this;
}
MyIterator operator++(int) {
MyIterator tmp(*this);
++(*this);
return tmp;
}
bool operator==(const MyIterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const MyIterator& other) const {
return !(*this == other);
}
operator const MyIterator() const {
return MyIterator(ptr_);
}
class const_iterator {
public:
using value_type = int;
using difference_type = long;
using pointer = const int*;
using reference = const int&;
using iterator_category = std::forward_iterator_tag;
const_iterator(int* ptr) : ptr_(ptr) {}
const_iterator& operator++() {
++ptr_;
return *this;
}
const_iterator operator++(int) {
const_iterator tmp(*this);
++(*this);
return tmp;
}
const int& operator*() const {
return *ptr_;
}
bool operator==(const const_iterator& other) const {
return ptr_ == other.ptr_;
}
bool operator!=(const const_iterator& other) const {
return !(*this == other);
}
private:
int* ptr_;
};
private:
int* ptr_;
};
这个自定义迭代器包含一个const_iterator,可以通过转换将其转换为const_iterator。示例中,将MyIterator转换为const MyIterator,但是由于其const_iterator的定义,可以将const MyIterator转换为const_iterator,以便在需要const迭代器的地方使用。
上一篇:不能将字典合并到列表中。