简体   繁体   中英

Iterator category

In code:

//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<std::bidirectional_iterator_tag,T>

    {
    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*&?
};

Basically what I'm asking is if I have my variable of type T** in iterator class is it right assumption that value type for this iterator will be T* and so on as I described in comments in code, right next to relevant lines.
Thank you.

The definition in the standard (section 24.3.2) is:

template<class Category, class T, class Distance = ptrdiff_t,
         class Pointer = T*, class Reference = T&>
struct iterator {
    typedef T value_type;
    typedef Distance difference_type;
    typedef Pointer pointer;
    typedef Reference reference;
    typedef Category iterator_category;
};

As you can see, the defaults are:

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

This is assuming that the iteration is over a container of elements of type T . If your container holds elements of type T* instead, the typedefs in your question would be correct.

You should define them as what you want them to be. pointer and reference are (the same as) the return types of the dereferencing operators you will be defining for your iterator class (ie, operator->() and operator*() respectively), so what you want these operators to return can guide how you want to define these typedefs.

In the comment you suggest that if you were inheriting from std::iterator , it would be from std::iterator<std::bidirectional_iterator_tag,T> . You can look in the Standard (as in interjay's answer) or your header files to see what typedefs this would provide, which will show you that you want T , T* , and T& , respectively, in order to be the same as what that would provide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM