iterator 订阅
迭代器(iterator)有时又称游标(cursor)是程序设计的软件设计模式,可在容器(container,例如链表或阵列)上遍访的接口,设计人员无需关心容器的内容。 展开全文
迭代器(iterator)有时又称游标(cursor)是程序设计的软件设计模式,可在容器(container,例如链表或阵列)上遍访的接口,设计人员无需关心容器的内容。
信息
外文名
iterator
别    称
游标卡尺
提出者
张康健
中文名
迭代器
适用领域范围
IT行业
迭代器解释
迭代器(iterator)是一种对象,它能够用来遍历标准模板库容器中的部分或全部元素,每个迭代器对象代表容器中的确定的地址。迭代器修改了常规指针的接口,所谓迭代器是一种概念上的抽象:那些行为上像迭代器的东西都可以叫做迭代器。然而迭代器有很多不同的能力,它可以把抽象容器和通用算法有机的统一起来。迭代器提供一些基本操作符:*、++、==、!=、=。这些操作和C/C++“操作array元素”时的指针接口一致。不同之处在于,迭代器是个所谓的复杂的指针,具有遍历复杂数据结构的能力。其下层运行机制取决于其所遍历的数据结构。因此,每一种容器型都必须提供自己的迭代器。事实上每一种容器都将其迭代器以嵌套的方式定义于内部。因此各种迭代器的接口相同,型号却不同。这直接导出了泛型程序设计的概念:所有操作行为都使用相同接口,虽然它们的型别不同。迭代器使开发人员能够在类或结构中支持foreach迭代,而不必整个实现IEnumerable或者IEnumerator接口。只需提供一个迭代器,即可遍历类中的数据结构。当编译器检测到迭代器时,将自动生成IEnumerable接口或者IEnumerator接口的Current,MoveNext和Dispose方法。1.迭代器是可以返回相同类型值的有序序列的一段代码;2.迭代器可用作方法、运算符或get访问器的代码体;3.迭代器代码使用yieldreturn语句依次返回每个元素,yield break将终止迭代;4.可以在类中实现多个迭代器,每个迭代器都必须像任何类成员一样有惟一的名称,并且可以在foreach语句中被客户端,代码调用如下所示:foreach(int x in SimpleClass.Iterator2){};5.迭代器的返回类型必须为IEnumerable和IEnumerator中的任意一种;6.迭代器是产生值的有序序列的一个语句块,不同于有一个 或多个yield语句存在的常规语句块;7.迭代器不是一种成员,它只是实现函数成员的方式,理解这一点是很重要的,一个通过迭代器实现的成员,可以被其他可能或不可能通过迭代器实现的成员覆盖和重载;8.迭代器块在C#语法中不是独特的元素,它们在几个方面受到限制,并且主要作用在函数成员声明的语义上,它们在语法上只是语句块而已;9.yield关键字用于指定返回的值。到达yieldreturn语句时,会保存当前位置。下次调用迭代器时将从此位置重新开始执行。 迭代器对集合类特别有用,它提供一种简单的方法来迭代不常用的数据结构(如二进制树)。迭代器是一种检查容器内元素并遍历元素的可带泛型数据类型。
收起全文
精华内容
下载资源
问答
  • Iterator

    千次阅读 2019-06-05 22:14:58
    Iterator

    Iterator

    Iterator:迭代器,它是Java集合的顶层接口(不包括 map 系列的集合,Map接口 是 map 系列集合的顶层接口)
    主要包含三种方法:

    1. hasNext()是否还有下一个元素。
    2. next()返回下一个元素。
    3. remove()删除当前元素。
    展开全文
  • iterator

    2017-08-16 16:04:01
    java iterator

    If you are just wandering over the collection to read all of the values, then there is no difference between using an iterator or the new for loop syntax, as the new syntax just uses the iterator underwater.

    If however, you mean by loop the old “c-style” loop:

    for(int i=0; i< list.size(); i++) {
    Object o = list.get(i);
    }
    Then the new for loop, or iterator, can be a lot more efficient, depending on the underlying data structure. The reason for this is that for some data structures, get(i) is an O(n) operation, which makes the loop an O(n2) operation. A traditional linked list is an example of such a data structure. All iterators have as a fundamental requirement that next() should be an O(1) operation, making the loop O(n).

    To verify that the iterator is used underwater by the new for loop syntax, compare the generated bytecodes from the following two Java snippets. First the for loop:

    List a = new ArrayList();
    for (Integer integer : a)
    {
    integer.toString();
    }
    // Byte code
    ALOAD 1
    INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator;
    ASTORE 3
    GOTO L2
    L3
    ALOAD 3
    INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object;
    CHECKCAST java/lang/Integer
    ASTORE 2
    ALOAD 2
    INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String;
    POP
    L2
    ALOAD 3
    INVOKEINTERFACE java/util/Iterator.hasNext()Z
    IFNE L3
    And second, the iterator:

    List a = new ArrayList();
    for (Iterator iterator = a.iterator(); iterator.hasNext();)
    {
    Integer integer = (Integer) iterator.next();
    integer.toString();
    }
    // Bytecode:
    ALOAD 1
    INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator;
    ASTORE 2
    GOTO L7
    L8
    ALOAD 2
    INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object;
    CHECKCAST java/lang/Integer
    ASTORE 3
    ALOAD 3
    INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String;
    POP
    L7
    ALOAD 2
    INVOKEINTERFACE java/util/Iterator.hasNext()Z
    IFNE L8
    As you can see, the generated byte code is effectively identical, so there is no performance penalty to using either form. Therefore, you should choose the form of loop that is most aesthetically appealing to you, for most people that will be the for-each loop, as that has less boilerplate code.

    for-each is syntactic sugar for using iterators (approach 2).

    You might need to use iterators if you need to modify collection in your loop. First approach will throw exception.

    for (String i : list) {
    System.out.println(i);
    list.remove(i); // throws exception modCount 和 expectedModCount不一致
    }

    Iterator it=list.iterator();
    while (it.hasNext()){
    System.out.println(it.next());
    it.remove(); // valid here
    }

    //打印并删除
    for (int i = 0; i < a.size(); i++) {
    System.out.println(a.get(i));
    a.remove(i);
    } //不会报错,但影响结果,可以从后往前删

    展开全文
  • Design Pattern - Iterator(C#)

    万次阅读 多人点赞 2019-02-11 16:59:36
    This structural code demonstrates the Iterator pattern which provides for a way to traverse (iterate) over a collection of items without detailing the underlying structure of the collection. ...

    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net 

    Definition

    Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

    Participants

        The classes and/or objects participating in this pattern are:

    • Iterator (AbstractIterator)
      • Defines an interface for accessing and traversing elements
    • ConcreteIterator (Iterator)
      • Implements the Iterator interface
      • Keeps track of the current position in the traversal of the aggregate
    • Aggregate (AbstractCollection)
      • Defines an interface for creating an Iterator object
    • ConcreteAggregate (Collection)
      • Implements the Iterator creation interface to return an instance of the proper ConcreteIterator

    Sample Code in C#


    This structural code demonstrates the Iterator pattern which provides for a way to traverse (iterate) over a collection of items without detailing the underlying structure of the collection.

    /*
     * Structural Iterator Design Pattern.
     */
    
    using System;
    using System.Collections;
    
    namespace Iterator.Sample
    {
        /// <summary>
        /// Startup class for Structural Iterator Design Pattern.
        /// </summary>
        internal static class Program
        {
            #region Methods
    
            /// <summary>
            /// Entry point into console application.
            /// </summary>
            private static void Main()
            {
                var a = new ConcreteAggregate {[0] = "Item A", [1] = "Item B", [2] = "Item C", [3] = "Item D"};
    
                // Create Iterator and provide aggregate.
                var i = new ConcreteIterator(a);
                Console.WriteLine("Iterating over collection:");
                var item = i.First();
                while (item != null)
                {
                    Console.WriteLine(item);
                    item = i.Next();
                }
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Aggregate' abstract class.
        /// </summary>
        internal abstract class Aggregate
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// Create iterator.
            /// </summary>
            /// <returns>
            /// The <see cref="Iterator"/>.
            /// </returns>
            public abstract Iterator CreateIterator();
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteAggregate' class.
        /// </summary>
        internal class ConcreteAggregate : Aggregate
        {
            #region Fields
    
            /// <summary>
            /// The items.
            /// </summary>
            private readonly ArrayList _items = new ArrayList();
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Gets the count.
            /// </summary>
            public int Count => _items.Count;
    
            #endregion
    
            #region Public Indexers
    
            /// <summary>
            /// Indexer.
            /// </summary>
            /// <param name="index">
            /// The index.
            /// </param>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public object this[int index]
            {
                get { return _items[index]; }
    
                set { _items.Insert(index, value); }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Create iterator.
            /// </summary>
            /// <returns>
            /// The <see cref="Iterator"/>.
            /// </returns>
            public override Iterator CreateIterator()
            {
                return new ConcreteIterator(this);
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Iterator' abstract class.
        /// </summary>
        internal abstract class Iterator
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// The current item.
            /// </summary>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public abstract object CurrentItem();
    
            /// <summary>
            /// The first.
            /// </summary>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public abstract object First();
    
            /// <summary>
            /// The is done.
            /// </summary>
            /// <returns>
            /// The <see cref="bool"/>.
            /// </returns>
            public abstract bool IsDone();
    
            /// <summary>
            /// The next.
            /// </summary>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public abstract object Next();
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteIterator' class.
        /// </summary>
        internal class ConcreteIterator : Iterator
        {
            #region Fields
    
            /// <summary>
            /// The aggregate.
            /// </summary>
            private readonly ConcreteAggregate _aggregate;
    
            /// <summary>
            /// The current.
            /// </summary>
            private int _current;
    
            #endregion
    
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="ConcreteIterator"/> class.
            /// </summary>
            /// <param name="aggregate">
            /// The aggregate.
            /// </param>
            public ConcreteIterator(ConcreteAggregate aggregate)
            {
                _aggregate = aggregate;
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The current item.
            /// </summary>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public override object CurrentItem()
            {
                return _aggregate[_current];
            }
    
            /// <summary>
            /// The first.
            /// </summary>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public override object First()
            {
                return _aggregate[0];
            }
    
            /// <summary>
            /// Gets whether iterations are complete.
            /// </summary>
            /// <returns>
            /// The <see cref="bool"/>.
            /// </returns>
            public override bool IsDone()
            {
                return _current >= _aggregate.Count;
            }
    
            /// <summary>
            /// The next.
            /// </summary>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public override object Next()
            {
                object ret = null;
    
                if (_current < _aggregate.Count - 1)
                {
                    ret = _aggregate[++_current];
                }
    
                return ret;
            }
    
            #endregion
        }
    }
    
    // Output:
    /*
    Iterating over collection:
    Item A
    Item B
    Item C
    Item D
    
    */

    This real-world code demonstrates the Iterator pattern which is used to iterate over a collection of items and skip a specific number of items each iteration.

    /*
     * Real-World Iterator Design Pattern.
     */
    
    namespace Iterator.RealWorld
    {
        using System;
        using System.Collections;
    
        /// <summary>
        /// The 'Aggregate' interface.
        /// </summary>
        internal interface IAbstractCollection
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// Create iterator.
            /// </summary>
            /// <returns>
            /// The <see cref="Iterator"/>.
            /// </returns>
            Iterator CreateIterator();
    
            #endregion
        }
    
        /// <summary>
        /// The 'Iterator' interface.
        /// </summary>
        internal interface IAbstractIterator
        {
            #region Public Properties
    
            /// <summary>
            /// Gets the current item.
            /// </summary>
            Item CurrentItem { get; }
    
            /// <summary>
            /// Gets a value indicating whether is done.
            /// </summary>
            bool IsDone { get; }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The first.
            /// </summary>
            /// <returns>
            /// The <see cref="Item"/>.
            /// </returns>
            Item First();
    
            /// <summary>
            /// The next.
            /// </summary>
            /// <returns>
            /// The <see cref="Item"/>.
            /// </returns>
            Item Next();
    
            #endregion
        }
    
        /// <summary>
        /// Startup class for Real-World Iterator Design Pattern.
        /// </summary>
        internal static class Program
        {
            #region Methods
    
            /// <summary>
            /// Entry point into console application.
            /// </summary>
            private static void Main()
            {
                // Build a collection
                var collection = new Collection
                {
                    [0] = new Item("Item 0"),
                    [1] = new Item("Item 1"),
                    [2] = new Item("Item 2"),
                    [3] = new Item("Item 3"),
                    [4] = new Item("Item 4"),
                    [5] = new Item("Item 5"),
                    [6] = new Item("Item 6"),
                    [7] = new Item("Item 7"),
                    [8] = new Item("Item 8")
                };
    
                // Create iterator.
                var iterator = new Iterator(collection) {Step = 2};
    
                // Skip every other item.
                Console.WriteLine("Iterating over collection:");
                for (Item item = iterator.First(); !iterator.IsDone; item = iterator.Next())
                {
                    Console.WriteLine(item.Name);
                }
            }
    
            #endregion
        }
    
        /// <summary>
        /// A collection item.
        /// </summary>
        internal class Item
        {
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="Item"/> class.
            /// </summary>
            /// <param name="name">
            /// The name.
            /// </param>
            public Item(string name)
            {
                Name = name;
            }
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Gets the name.
            /// </summary>
            public string Name { get; }
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteAggregate' class.
        /// </summary>
        internal class Collection : IAbstractCollection
        {
            #region Fields
    
            /// <summary>
            /// The items.
            /// </summary>
            private readonly ArrayList _items = new ArrayList();
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Gets the count.
            /// </summary>
            public int Count => _items.Count;
    
            #endregion
    
            #region Public Indexers
    
            /// <summary>
            /// Indexer.
            /// </summary>
            /// <param name="index">
            /// The index.
            /// </param>
            /// <returns>
            /// The <see cref="object"/>.
            /// </returns>
            public object this[int index]
            {
                get { return _items[index]; }
    
                set { _items.Add(value); }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// Create iterator.
            /// </summary>
            /// <returns>
            /// The <see cref="Iterator"/>.
            /// </returns>
            public Iterator CreateIterator()
            {
                return new Iterator(this);
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteIterator' class.
        /// </summary>
        internal class Iterator : IAbstractIterator
        {
            #region Fields
    
            /// <summary>
            /// The collection.
            /// </summary>
            private readonly Collection _collection;
    
            /// <summary>
            /// The current.
            /// </summary>
            private int _current;
    
            /// <summary>
            /// The step.
            /// </summary>
            private int _step = 1;
    
            #endregion
    
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="Iterator"/> class.
            /// </summary>
            /// <param name="collection">
            /// The collection.
            /// </param>
            public Iterator(Collection collection)
            {
                _collection = collection;
            }
    
            #endregion
    
            #region Public Properties
    
            /// <summary>
            /// Gets the current item.
            /// </summary>
            public Item CurrentItem => _collection[_current] as Item;
    
            /// <summary>
            /// Gets a value indicating whether is done.
            /// </summary>
            public bool IsDone => _current >= _collection.Count;
    
            /// <summary>
            /// Gets or sets the step.
            /// </summary>
            public int Step
            {
                get { return _step; }
    
                set { _step = value; }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The first.
            /// </summary>
            /// <returns>
            /// The <see cref="Item"/>.
            /// </returns>
            public Item First()
            {
                _current = 0;
                return _collection[_current] as Item;
            }
    
            /// <summary>
            /// The next.
            /// </summary>
            /// <returns>
            /// The <see cref="Item"/>.
            /// </returns>
            public Item Next()
            {
                _current += _step;
                if (!IsDone)
                {
                    return _collection[_current] as Item;
                }
    
                return null;
            }
    
            #endregion
        }
    }
    
    // Output:
    /*
    Iterating over collection:
    Item 0
    Item 2
    Item 4
    Item 6
    Item 8
    
    */

     

    展开全文
  • class reverse_iterator { protected:  _Iterator current; //对应之正向迭代器 public:  //逆向迭代器的5种associated types都和其相对应  typedef typename iterator_traits::iterator_category  ite


    1.迭代器适配器reverse_iterator

    template <class _Iterator>
    class reverse_iterator
    {
    protected:
      _Iterator current;  //对应之正向迭代器

    public:

      //逆向迭代器的5种associated types都和其相对应

      typedef typename iterator_traits<_Iterator>::iterator_category
              iterator_category;
      typedef typename iterator_traits<_Iterator>::value_type
              value_type;
      typedef typename iterator_traits<_Iterator>::difference_type
              difference_type;
      typedef typename iterator_traits<_Iterator>::pointer
              pointer;
      typedef typename iterator_traits<_Iterator>::reference
              reference;

      typedef _Iterator iterator_type //代表正向迭代器
      typedef reverse_iterator<_Iterator> _Self //代表逆向迭代器

    public:
      reverse_iterator() {}
      explicit reverse_iterator(iterator_type __x) : current(__x) {}

      reverse_iterator(const _Self& __x) : current(__x.current) {}
    #ifdef __STL_MEMBER_TEMPLATES
      template <class _Iter>
      reverse_iterator(const reverse_iterator<_Iter>& __x)
        : current(__x.base()) {}
    #endif /* __STL_MEMBER_TEMPLATES */

      iterator_type base() const { return current; }  //取出对应的正向迭代器

      //对逆向迭代器取值,就是将对应之正向迭代器退一位取值

      reference operator*() const {
        _Iterator __tmp = current;
        return *--__tmp;
      }
    #ifndef __SGI_STL_NO_ARROW_OPERATOR
      pointer operator->() const { return &(operator*()); }

    #endif /* __SGI_STL_NO_ARROW_OPERATOR */

      //前进变后退,后退变成前进

      _Self& operator++() {
        --current;
        return *this;
      }
      _Self operator++(int) {
        _Self __tmp = *this;
        --current;
        return __tmp;
      }
      _Self& operator--() {
        ++current;
        return *this;
      }
      _Self operator--(int) {
        _Self __tmp = *this;
        ++current;
        return __tmp;
      }

      _Self operator+(difference_type __n) const {
        return _Self(current - __n);
      }
      _Self& operator+=(difference_type __n) {
        current -= __n;
        return *this;
      }
      _Self operator-(difference_type __n) const {
        return _Self(current + __n);
      }
      _Self& operator-=(difference_type __n) {
        current += __n;
        return *this;
      }
      reference operator[](difference_type __n) const { return *(*this + __n); }  
    };

    2.rbegin,rend

      reverse_iterator rbegin() { return reverse_iterator(end()); }
      reverse_iterator rend() { return reverse_iterator(begin()); }

     


    展开全文
  • php之IteratorIterator个人理解

    千次阅读 2018-10-01 11:38:44
    php IteratorIterator个人理解IteratorIterator简介重点理解代码演示运行结果:结果分析一点补充 最近有重新开始捣鼓laravel的源码了,一年多没用实在是忘的差不多了,每次看都会从中学到很多,不懂就赶紧查手册。...
  • JAVA iteratoriterator模式

    千次阅读 2016-04-28 14:33:47
    Iterator 模式 JAVA Collection 接口中有一个方法,iterator(),而Set,List,Queue都继承自Collection。 由于对Collection对象的遍历需求,进而产生了iterator。 这里介绍iterator模式及Java Iterator
  • const_iteratoriterator

    2018-04-04 09:39:09
    ::iterator it1 = v.begin();vector&lt;int&gt;::iterator const it2 = v.begin();const it2------&gt;vector&lt;int&gt;::iterator it2本身是const,即it2本身的值不能改变,即不能指向其他...
  • Iterator接口

    2019-02-24 15:15:32
    1:所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现了Iterator接口的对象。 2:Iterator对象称作迭代器,用以方便的实现对容器内元素的遍历操作。 3:Iterator接口定义了如下方法 可以将...
  • 如果你传递过来一个const类型的容器,那么只能用const_iterator来遍历。 void Method(const vector vInt) { vector::const_iterator iter; } 示例: vector ivec; vector::const_iterator citer1 =...
  • Iterator对象

    2018-12-13 14:58:01
    Iterator对象, 是一个引用型变量,他存在的意义在于,为了遍历容器对象中的元素而不暴露容器对象内部的细节。 iterator()方法是容器变量使用,返回一个Iterator对象。该对象也是一个容器。 因为他里面存放着...
  • 最近研究iterator,看了下const_iterator和const iterator的使用,记录下来,以供以后参考。
  • Iterator迭代器

    2020-12-21 17:05:20
    Iterator 接口 文档关于 Iterator 接口的介绍:遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理...
  • Iterator原理

    千次阅读 2016-08-15 13:06:21
    Iterator用于遍历集合中的元素,适用于不知道集合内部结构的情况。用户不再与集合类交互,而是与Iterator交互,其清楚知道集合类的内部状态,通过控制iterator达到遍历集合的目的。
  • 有些版本的insert和erase函数要求使用iterator。如果你需要调用这些函数,那么必须使用iterator。const和reverse型的迭代器不能满足这些函数要求。要想隐式将一个const_iterator转换成iterator式不可能的从reverse_...
  • const iteratoriterator本身是个常量,iterator本身里面存的是指针,也就是iterator的值,也就是那个指针不能改变,也就是不能指向其他的位置,但是所指向的位置的元素是可以通过这个iterator来改变的...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 76,912
精华内容 30,764
关键字:

iterator