iterator_trait的典型用例是什么? [英] What are the typical use cases of an iterator_trait

查看:144
本文介绍了iterator_trait的典型用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,所以请耐心等待。我想了解STL iterator_traits。在C ++标准库一书中,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
}

所以它似乎我重新公开 T 已暴露的子类型。继续前进,本书给出了如何使用它的示例,类似于以下内容

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
    .....

我的问题是为什么我需要这个iterator_traits结构,如果想要获得 value_type ,我不能直接从 MyIterator 获得它吗?我的困惑似乎来自我(肯定是不正确的)理解,即子类型的信息必须来自用于实例化iterator_trait的模板< class T> 。所以如果你能解释一下,最好用一个例子说明为什么以及在哪里需要iterator_traits,这将非常有帮助。

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.

推荐答案

指针一个数组可以用作随机访问迭代器。

Pointers into an array can be used as random access iterators.

需要一些一致的方法来获取这些类型的指针(显然不能声明类型)作为嵌套类型,因为只有类可以有嵌套类型)和类类型迭代器。 traits类模板提供了这种一致的方式。

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.

iterator_traits 类模板专门用于指针,如:

The iterator_traits class template is specialized for pointers like so:

template <typename T>
struct iterator_traits<T*>
{
    typedef std::random_access_iterator_tag iterator_category;
    typedef T                               value_type;
    typedef T*                              pointer;
    typedef T&                              reference;
    typedef std::ptrdiff_t                  difference_type;
};

这篇关于iterator_trait的典型用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆