iterator_trait 的典型用例有哪些
我是 C++ 新手,所以请耐心等待。我正在尝试理解 STL iterator_traits
。在《C++ 标准库》一书中,结构体 iterator_traits
定义如下:
template <class T>
struct iterator_traits {
typedef typename T::value_type value_type;
typedef typename T::difference_type difference_type;
typedef typename T::iterator_category iterator_category;
typedef typename T::pointer pointer;
typedef typename T::reference reference;
};
所以在我看来,它正在重新公开 T
已经公开的子类型。更进一步,本书给出了如何使用它的示例,如下所示
template <class MyIterator>
void do_something(MyIterator start, MyIterator end) {
typedef typename iterator_traits<MyIterator>::value_type value_type;
value_type v = *start;
.....
}
我的问题是,如果我的想法是获取 ,为什么这里需要这个
,我不能直接从iterator_traits
结构value_typeMyIterator
获取它吗?我的困惑似乎源于我(肯定不正确)的理解,即子类型的信息必须源自用于实例化 iterator_trait
的 template
。因此,如果您能解释一下,最好用一个例子来解释为什么以及在哪里需要 iterator_traits,那将非常有帮助。
I am new to C++ so please bear with me. I am trying to understand STL iterator_traits
. In the book "The C++ Standard Library" the structure iterator_traits
is defined as follows:
template <class T>
struct iterator_traits {
typedef typename T::value_type value_type;
typedef typename T::difference_type difference_type;
typedef typename T::iterator_category iterator_category;
typedef typename T::pointer pointer;
typedef typename T::reference reference;
};
So it seems to me that it is re-exposing the subtypes that T
already exposes. Moving ahead further, the book gives an example of how to use it, which is something like the following
template <class MyIterator>
void do_something(MyIterator start, MyIterator end) {
typedef typename iterator_traits<MyIterator>::value_type value_type;
value_type v = *start;
.....
}
My question is why do I need this iterator_traits
structure here, if the idea was to obtain the value_type
, couldn't I have obtained it from MyIterator
directly ? My confusion seems to arise from my (surely incorrect) understanding that the information of the subtypes have to be sourced from the template <class T>
used to instantiate the iterator_trait
. So if you could explain, and preferably with an example why and where would I need iterator_traits that would be very helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
指向数组的指针可以用作随机访问迭代器。
需要有一些一致的方法来获取指针(显然不能将类型声明为嵌套类型,因为只有类可以具有嵌套类型)和类类型迭代器的这些类型。 Traits 类模板提供了这种一致的方式。
iterator_traits 类模板专门用于指针,如下所示:
Pointers into an array can be used as random access iterators.
There needs to be some consistent way to get these types both for pointers (which obviously can't have the types declared as nested types, since only classes can have nested types) and for class-type iterators. The traits class template provides this consistent way.
The
iterator_traits
class template is specialized for pointers like so: