Iterator usage and generator usage

Source: Internet
Author: User

Iterator usage and generator usage


What is an iterator?

Iterator is a mechanism for Traversing elements in one or more containers in a certain order. for example, a for loop is the simplest Iterator, traversing an array is also an iterative process. GOF defines a method to access each element in a container object without exposing the internal details of the object. An iterator is also called an Enumerator. Its structure is as follows:

Iterator Structure

 

The iterator is actually to maintain a current pointer. This pointer can point to the current element, return the current element, and move it to the next element, this pointer can be used to traverse all elements of the container. The iterator generally has at least the following methods:

First ();// Move the pointer to the first position or obtain the first element.

GetCurrent ();// Obtain the element currently pointed

MoveNext ();// Move to the next element

 

 

How to Use the iterator

Since the iterator encapsulates the implementation details and provides an interface for convenient access to container elements, we should first understand the iterator from the perspective of usage, let's see how the iterator is used in various languages.

 

Iterator in C ++:

Void TestIterator () {vector <int> vec; // defines a container for (int I = 0; I <5; I ++) {vec. push_back (I * 2); // Add element} // use an iterator to access each element in the container cout <"iterator vector:" <endl; for (vector <int>: iterator itr = vec. begin (); itr! = Vec. end (); itr ++) {cout <* itr <"; // itr is a pointer pointing to the current element, so we need to obtain the element value} cout <endl; map <int, string> student; // create a map, corresponding student ID-name key-Value Pair // Add element student. insert (pair <int, string> (1, "Zhang San"); student. insert (pair <int, string> (3, "Wang Wu"); student. insert (pair <int, string> (2, ""); // traverses the cout element in the container <"iterator map:" <endl; for (map <int, string >:: iterator itr = student. begin (); itr! = Student. end (); itr ++) {cout <itr-> first <"-->" <itr-> second <endl ;}}

Result:


Iterator vector:

0 2 4 6 8

Iterator map:

1 --> Zhang San

2 --> Li Si

3 --> Wang Wu

 

Containers in c ++ (such as vector, map, list, and set) generally provide four iterators:

Iterator: indicates a Forward Iteration. it traverses the previous and later stages to modify the value of an element.

Const_iterator: positive constant iteration, but the value of the element cannot be modified because it points to the reference of const.

Reverse_iterator: reverse iteration, traversing from the back to the front, you can modify the value of the element

Const_reverse_iterator: reverse constant iteration, but the element value cannot be modified because it points to the reference of const.

Each iterator provides a pair of sign begin and end at the beginning and end. The relationship is as follows:

Iterator type

Start position mark

End position mark

Description

Iterator

Begin ()

End ()

Forward Iteration

Const_iterator

Cbegin ()

Cend ()

Positive constant Iteration

Reverse_iterator

Rbegin ()

Rend ()

Reverse Iteration

Const_reverse_iterator

Crbegin ()

Crend ()

Reverse constant Iteration

 

The corresponding information is as follows:


Figure 1: normal Iteration

 

Figure 2: Constant Value Iteration

 

 

Java iterator:

Public static void testIterator () {// create a List list <Integer> list = new ArrayList <Integer> (); List. add (4); // add the element list. add (3); list. add (7); // returns an Iterator and traverses the iterator element in the list <Integer> Iterator = list. iterator (); while (iterator. hasNext () {Integer value = iterator. next (); System. out. print (value + "");} System. out. println (); // returns the ListIterator iterator and traverses the ListIterator <Integer> listIterator = list. listIterator (list. size (); System. out. println ("ListIterator:"); while (listIterator. hasPrevious () {Integer value = listIterator. previous (); System. out. print (value + "");} System. out. println ();}

Result:

Iterator begin to end:

4 3 7

ListIterator end to begin:

7 3 4

 

The List interface and its implementation classes in Java can return iterator through Iterator (), or listIterator through listIterator () and ListIterator (int index.

Iterator and ListIterator are both iterators, and ListIterator inherits from Iterator. Iterator can only traverse the list. It can only traverse the list from the front to the back. ListIterator can modify the list and traverse the list either forward or backward. For more information about Iterator and ListIterator, see the official API: Iterator and ListIterator.

 

Iterator in JavaScript

In JavaScript, the container is of the Array type. The standard does not provide the description and implementation of the corresponding iterator, but we can implement a simple iterator function by ourselves:

<Script type = "text/javascript"> // create an iterator. The input must be Array-type data function makeIterator (array) {var index = 0; return {hasNext: function () {return index <array. length;}, next: function () {return this. hasNext? Array [index ++]: null ;}, current: function () {return array [index] ;};} // create an Array and assign the value var mycars = new Array (); mycars [0] = "Saab"; mycars [1] = "Volvo "; mycars [2] = "BMW"; // generates an iterator for the array mycars, and traverses the data element var iterator = makeIterator (mycars) through the iterator; while (iterator. hasNext () {document. write (iterator. next () + '<br>') ;}</script>

Result:

Saab

Volvo

BMW

 

Mozilla has added the iterator function for JavaScript 1.7, but it can only be used on Firefox. For example:

<Script type = "application/javascript; version = 1.7"> var lang = {name: 'javascript ', birthYear: 1995, age: 19 }; // generate an Iterator var itr = Iterator (lang); document. write ('key-value: '+' <br> '); for (var key in itr) {document. write (key + '<br>');} // This Iterator traverses each key value var itr2 = Iterator (lang, false); document. write ('key: '+' <br> '); for (var key in itr2) {document. write (key + '<br>');} // This iterator traverses each index and value var arrs = ['javascript ', 'python', 'haskell']; var itr3 = Iterator (arrs, false); document. write ('index-value: '+' <br> '); for (let [I, value] in itr3) {document. write (I + ':' + value + '<br>') ;}</script>

Result:

Key-value:

Name, JavaScript

Birthyear, 1995

Age, 19

Key:

Name, JavaScript

Birthyear, 1995

Age, 19

Index-value:

0: JavaScript

1: Python

2: Haskell

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.