- 外文名
- iterator
- 别 称
- 游标卡尺
- 提出者
- 张康健
- 中文名
- 迭代器
- 适用领域范围
- IT行业
-
Iterator
2019-06-05 22:14:58 -
iterator
2017-08-16 16:04:01java iteratorIf 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分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!... Definition Provide a way to access the elements of an aggregate object sequentially without exposing its ...分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击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 */
- Iterator (AbstractIterator)
-
iterator adapter reverse_iterator
2017-06-06 09:40:06class reverse_iterator { protected: _Iterator current; //对应之正向迭代器 public: //逆向迭代器的5种associated types都和其相对应 typedef typename iterator_traits::iterator_category ite1.迭代器适配器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:44php IteratorIterator个人理解IteratorIterator简介重点理解代码演示运行结果:结果分析一点补充 最近有重新开始捣鼓laravel的源码了,一年多没用实在是忘的差不多了,每次看都会从中学到很多,不懂就赶紧查手册。... -
JAVA iterator与iterator模式
2016-04-28 14:33:47Iterator 模式 JAVA Collection 接口中有一个方法,iterator(),而Set,List,Queue都继承自Collection。 由于对Collection对象的遍历需求,进而产生了iterator。 这里介绍iterator模式及Java Iterator -
iterator和const iterator 和 const_iterator的区别
2017-10-16 19:55:13众所周知,iterator就是一个灵活的迭代器,而const iterator 和 const_iterator是啥?接下来,我来讲讲:const iterator(const迭代器)const迭代器,顾名思义,就是不能改变的迭代器,是常量,其性质是由const决定... -
const_iterator与iterator
2018-04-04 09:39:09::iterator it1 = v.begin();vector<int>::iterator const it2 = v.begin();const it2------>vector<int>::iterator it2本身是const,即it2本身的值不能改变,即不能指向其他... -
Iterator接口
2019-02-24 15:15:321:所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现了Iterator接口的对象。 2:Iterator对象称作迭代器,用以方便的实现对容器内元素的遍历操作。 3:Iterator接口定义了如下方法 可以将... -
iterator与const_iterator及const iterator区别
2016-03-06 16:08:14如果你传递过来一个const类型的容器,那么只能用const_iterator来遍历。 void Method(const vector vInt) { vector::const_iterator iter; } 示例: vector ivec; vector::const_iterator citer1 =... -
Iterator对象
2018-12-13 14:58:01Iterator对象, 是一个引用型变量,他存在的意义在于,为了遍历容器对象中的元素而不暴露容器对象内部的细节。 iterator()方法是容器变量使用,返回一个Iterator对象。该对象也是一个容器。 因为他里面存放着... -
iterator、const_iterator和const iterator的区别
2015-07-27 23:32:57最近研究iterator,看了下const_iterator和const iterator的使用,记录下来,以供以后参考。 -
Iterator迭代器
2020-12-21 17:05:20Iterator 接口 文档关于 Iterator 接口的介绍:遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理... -
Iterator原理
2016-08-15 13:06:21Iterator用于遍历集合中的元素,适用于不知道集合内部结构的情况。用户不再与集合类交互,而是与Iterator交互,其清楚知道集合类的内部状态,通过控制iterator达到遍历集合的目的。 -
26 iterator优于const_iterator、reverse_iteratorj及const_reverse_iterator
2018-07-04 10:29:09有些版本的insert和erase函数要求使用iterator。如果你需要调用这些函数,那么必须使用iterator。const和reverse型的迭代器不能满足这些函数要求。要想隐式将一个const_iterator转换成iterator式不可能的从reverse_... -
C++ iterator用法
2014-03-25 21:18:56迭代器(iterator)是一中检查容器内元素并遍历元素的数据类型。(1) 每种容器类型都定义了自己的迭代器类型,如vector:vector<int>::iterator iter;这条语句定义了一个名为iter的变量,它的数据类型是由vector&... -
-
LeetCode_155. 最小栈
-
第5章-搜索
-
易语言开发通达信DLL公式接口
-
三维地图GIS大数据可视化
-
Soul源码学习 - 数据同步的一个问题记录
-
中红外氟化物激光晶体的生长和性能优化研究
-
Weblogic LDAP 远程代码执行漏洞(CVE-2021-2109)
-
Soul 源码分析09 SOUL admin/bootstrap cluster
-
flexbox card的小例子
-
MATLAB潮流计算程序
-
调试小记
-
【2021】UI自动化测试框架(Selenium3)
-
第3章 入门程序、常量、变量
-
PTA--1002 写出这个数 (20分)
-
亿度云盘~Java小白入门实战
-
PHP--简单Demo
-
【数据分析-随到随学】Hive详解
-
在Golang中获取DNS记录
-
kubernetes-dashboard.yaml
-
bianyiqi.zip