E đọc về cách cài đặt lại iterator thì thấy có 2 kiểu làm chính như sau:
1/
template <typename T>
class MyContainer
{
public:
typedef int size_type;
class iterator
{
public:
typedef iterator self_type;
typedef T value_type;
typedef T& reference;
typedef T* pointer;
typedef std::forward_iterator_tag iterator_category;
typedef int difference_type;
iterator(pointer ptr) : ptr_(ptr) { }
self_type operator++() { self_type i = *this; ptr_++; return i; }
self_type operator++(int junk) { ptr_++; return *this; }
reference operator*() { return *ptr_; }
pointer operator->() { return ptr_; }
bool operator==(const self_type& rhs) { return ptr_ == rhs.ptr_; }
bool operator!=(const self_type& rhs) { return ptr_ != rhs.ptr_; }
private:
pointer ptr_;
};
// implement method ...
iterator begin() return iterator(data_);
iterator end() return iterator(data_ + size_);
private:
T* data_;
size_type size_;
};
2/
template<class T>
class myIterator : public std::iterator<std::forward_iterator_tag, T>
{
// định nghĩa các operator
};
A/c cho e hỏi trong kiểu thứ 2, việc kế thừa này để làm gì ạ? Vì trong std::iterator e chỉ thấy như kiểu nó là 1 interface để myIterator tuân theo chứ ngoài ra ko còn mục đích gì khác!
Có phải những container như vector
,… cũng có 1 nested class iterator bên trong như kiểu 1
phía trên phải không ạ? Với lại iterator_traits
là để làm gì v ạ? e đã tìm hiểu r nhưng vẫn ko hiểu lắm!