简体   繁体   English

迭代器类别

[英]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. 基本上,我要问的是迭代器类中是否有类型为T **的变量,是否正确地假设此迭代器的值类型将为T *,依此类推,如我在代码注释中所述,紧挨相关行。
Thank you. 谢谢。

The definition in the standard (section 24.3.2) is: 标准中的定义(第24.3.2节)为:

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 . 假设迭代是在类型T的元素的容器上进行的。 If your container holds elements of type T* instead, the typedefs in your question would be correct. 如果您的容器代之以T*类型的元素,那么您问题中的typedef将是正确的。

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. pointerreference与将为迭代器类定义的解引用运算符的返回类型(相同)(即分别为operator->()operator*() ),因此您希望这些运算符返回的内容可以指导您要如何定义这些typedef。

In the comment you suggest that if you were inheriting from std::iterator , it would be from std::iterator<std::bidirectional_iterator_tag,T> . 在注释中,您建议如果您继承自std::iterator ,那么它将继承自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. 您可以查看Standard(如interjay的回答)或头文件中的内容,以了解将提供什么typedef,它们将分别显示您想要TT*T& ,以便与将提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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