一千萬個為什麽

搜索
當前位置: 首頁 > 叠代器類別

叠代器類別

在代碼中:

//I know that to get this effect (being able to use it with std algorithms) I can inherit like I did in line below:

    class Iterator //: public std::iterator

    {
    private:
        T** itData_;
    public:
        //BUT I WOULD LIKE TO BE ABLE TO DO IT BY HAND AS WELL
        typedef std::bidirectional_iterator_tag iterator_category;
        typedef T* value_type;//SHOULD IT BE T AS value_type or T*?
        typedef std::ptrdiff_t difference_type;
        typedef T** pointer;//SHOULD IT BE T* AS pointer or T**?
        typedef T*& reference;//SHOULD IT BE T& AS reference or T*&?
};

基本上我要問的是,如果我在叠代器類中有T **類型的變量,那麽正確的假設這個叠代器的值類型將是T *,正如我在代碼中的註釋中描述的那樣,緊挨著相關的行。結果 謝謝。

最佳答案

標準(第24.3.2節)中的定義是:

template
struct iterator {
    typedef T value_type;
    typedef Distance difference_type;
    typedef Pointer pointer;
    typedef Reference reference;
    typedef Category iterator_category;
};

如您所見,默認值為:

typedef T value_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef T& reference;

這假設叠代是在 T 類型的元素的容器上。如果您的容器包含 T * 類型的元素,那麽您問題中的typedef將是正確的。

轉載註明原文: 叠代器類別