6/9/2015assoc. prof. stoyan bonev1 cos220 concepts of pls aubg, cos dept lecture 11 iteration based...
TRANSCRIPT
04/21/23 Assoc. Prof. Stoyan Bonev 1
COS220 Concepts of PLs AUBG, COS dept
Lecture 11
Iteration Based on Data Structures
Reference: R.Sebesta, Section 8.3.4 Lafore, Chap 15
04/21/23 Assoc. Prof. Stoyan Bonev 2
Lecture Contents:
• Introducing the concept of iterating through data_structure elements
• Internal iterator• External iterator
– Implicit iterator– Explicit iterator
• Examples
04/21/23 Assoc. Prof. Stoyan Bonev 3
Iteration that depends on data structures:
• Rather than having– an index variable (Counter Controlled Loop) or– bool expression (Logically Controlled Loop)
• to dictate the number of iterations, here we have LOOPS whose number of iterations depends on the current number of data items /elements/ within the data structure.
04/21/23 Assoc. Prof. Stoyan Bonev 4
The rule:
• Data based iteration statement uses an abstract defined dynamic data structure and a user defined function to go through the structure’s elements. Such a function is called an internal iterator.
• External iterator – a pointer-like type that references elements of a container and which is used to navigate through a container object.
04/21/23 Assoc. Prof. Stoyan Bonev 5
Data structure Function
Borland Container Class Library
List forEach()actionFunc()
Queue firstThat()testFunc()
lastThat()
STL Standard Template Library
Class template vector<int> vector<int> theV;
vector<int>::iterator it;
for(i=0; i<theV.size(); i++) cout<<theV[i];
for(it=theV.begin(); it!=theV.end(); it++) cout<<*it;
Abstract Data TypesFor
Dynamic Data Structures: List, Queue
CCL
Class Hierarchy and
Selected Classes
04/21/23 Assoc. Prof. Stoyan Bonev 8
CCL – class hierarchy
Object
| \ \ \
Sortable Association ContainerError
04/21/23 Assoc. Prof. Stoyan Bonev 9
CCL – class hierarchy
Container| \ \ \
Collection Stack Queue Deque
| \ \ \AbstractArray List DoubleList HashTable
/ \ |Array SortedArray Bag
Set Dictionary
04/21/23 Assoc. Prof. Stoyan Bonev 10
CCL – class hierarchy
• List – a linked list. Items are inserted and deleted only at head of list. Fast to iterate through list, slow to access a particular item.
• DoubleList – a linked list. Items inserted and deleted from both ends of list.
• Queue – items in at end of queue, items out at the other end on FIFO basis.
• Deque – double-ended queue, combination of stack and queue. Items pushed and popped on either end of deque (a special kind of double list)
04/21/23 Assoc. Prof. Stoyan Bonev 11
List in CCL
CCL: the List class (#include <list.h>)
Methods:
add() – add object to head of list
detach() – remove object from head of list
destroy() – remove object from head of list and delete it
peekHead() – examine object at head of list
04/21/23 Assoc. Prof. Stoyan Bonev 12
Queue in CCL
CCL: the Queue class (#include <queue.h>)Methods:
put() – add object to head of queueget() – remove object from tail of queuepeekLeft() – examine object at head of queuepeekRight() – examine object at tail of queue
04/21/23 Assoc. Prof. Stoyan Bonev 13
Container in CCL
CCL: the Container class Methods:forEach()– the member function that
performs the same action on each itemfirstThat()– find first object satisfying
conditionlastThat() – find last object satisfying
condition
Internal Iterators
04/21/23 Assoc. Prof. Stoyan Bonev 15
Structure Iterators
• Structure Iterator construct is a loop similar to for except that the control mechanism is specified as a user defined subroutine like CCL member functions forEach(), firstThat(), lastThat().
• The function is called at the beginning of each iteration, and each time it is called, the function returns an element from a particular data structure in some order.
04/21/23 Assoc. Prof. Stoyan Bonev 16
Structure Iterators
• forEach() – the member function that performs the same action on each item. It requires you to tell it what action you want to perform on each item, you do this by passing it the address of a function as an argument.
• A function address is represented by its name alone, with no parentheses (C/C++ syntax).
• Iteration involves the use of iterator classes. These iterator classes are friends of the Container classes. They contain the mechanism to implement forEach() and similar functions.
04/21/23 Assoc. Prof. Stoyan Bonev 17
Container Class Library
CCL: the List class:
method forEach()
oop7a.cpp
oop7a.exe
04/21/23 Assoc. Prof. Stoyan Bonev 18
Container Class LibraryFirst: to create a list (instance of class List): List ls;
Second; to populate the list created (add four strings to the list)
String s1("1111"), s2("2222"), s3("3333"), s4("4444"); ls.add(s1); ls.add(s2); ls.add(s3); ls.add(s4);
Third: to perform action on each item
ls.forEach(actionFunc, 0);
Fourth; Define a function to perform action on each object in List
void actionFunc(Object& obj, void *) { cout <<"\nList element is:" << obj; }
04/21/23 Assoc. Prof. Stoyan Bonev 19
Container Class Library
CCL: the List class:
method forEach()
oop7a.cpp
oop7a.exe
04/21/23 Assoc. Prof. Stoyan Bonev 20
04/21/23 Assoc. Prof. Stoyan Bonev 21
Container Class Library
CCL: the List class:
methods firstThat(), lastThat()
oop7ba.cpp
oop7ba.exe
04/21/23 Assoc. Prof. Stoyan Bonev 22
Container Class LibraryFirst: to create a list (instance of class List): List ls;
Second; to populate the list created (add four strings to the list) String s1("1111"), s2("2222"), s3("3333"), s4("4444"); ls.add(s1); ls.add(s2); ls.add(s3); ls.add(s4);
Third: to perform action on each item: // test lastthat method String& temp=(String&)ls.lastThat(testFunc, 0); if(temp!=NOOBJECT) { cout << "\n\n\nlast That Match: "<<temp; }
else cout << "\n\n\nlastThat No match";
Fourth; Define a function to perform action on each object in List int testFunc(const Object& obj, void*){ String& tmp=(String&) obj; return !strcmp(tmp, "4444");}
04/21/23 Assoc. Prof. Stoyan Bonev 23
Container Class LibraryFirst: to create a list (instance of class List): List ls;
Second; to populate the list created (add four strings to the list) String s1("1111"), s2("2222"), s3("3333"), s4("4444"); ls.add(s1); ls.add(s2); ls.add(s3); ls.add(s4);
Third: to perform action on each item: // test firstthat method temp=(String&)ls.firstThat(testFunc, 0); if(temp!=NOOBJECT) { cout << "\n\n\nfirst That Match: "<<temp; }
else cout << "\n\n\nfirstThat No match";
Fourth; Define a function to perform action on each object in List int testFunc(const Object& obj, void*){ String& tmp=(String&) obj; return !strcmp(tmp, "4444");}
04/21/23 Assoc. Prof. Stoyan Bonev 24
Container Class Library
CCL: the List class:
methods firstThat(), lastThat()
oop7ba.cpp
oop7ba.exe
04/21/23 Assoc. Prof. Stoyan Bonev 25
From List to Queue
.
04/21/23 Assoc. Prof. Stoyan Bonev 27
Container Class Library
CCL: the Queue class: methods forEach(), firstThat(), lastThat()
oop7bb.cpp
oop7bb.exe
04/21/23 Assoc. Prof. Stoyan Bonev 28
Container Class Library
First: to create a queue (instance of class Queue): Queue q;
Second; to populate the queue (add four dates to the queue) Date * pd1 = new Date(1, 10, 2009); Date * pd2 = new Date(2, 15, 2010); Date * pd3 = new Date(3, 20, 2011); Date * pd4 = new Date(4, 25, 2012); q.put(*pd1); // put four dates to the queue q q.put(*pd2); q.put(*pd3); q.put(*pd4);
04/21/23 Assoc. Prof. Stoyan Bonev 29
Container Class Library
Third: to perform action on each item: q.forEach(actionFunc, 0); // perform action on each item
Date& temp=(Date&)q.lastThat(testFunc, 0); // test lastthat method if(temp!=NOOBJECT) { cout << "\n\n\nlast That Match: "<<temp; }
else cout << "\n\n\nlastThat No match";
temp=(Date&)q.firstThat(testFunc, 0); // test firstthat method if(temp!=NOOBJECT) { cout << "\n\n\nfirst That Match: "<<temp; }
else cout << "\n\n\nfirstThat No match";
Fourth; Define a function to perform action on each object in Queue void actionFunc(Object& obj, void*) { cout <<"\nQueue element is:"<<obj; }
int testFunc(const Object& obj, void*){ Date& tmp=(Date&) obj; return (tmp.Month()==3) ? 1 : 0;}
04/21/23 Assoc. Prof. Stoyan Bonev 30
Container Class Library
CCL: the Queue class: methods forEach(), firstThat(), lastThat()
oop7bb.cpp
oop7bb.exe
04/21/23 Assoc. Prof. Stoyan Bonev 31
External Iterators
04/21/23 Assoc. Prof. Stoyan Bonev 33
The Iterator concept
An iterator may be thought of as a type of pointer which has two primary operations:– referencing one particular element in the collection
object (called element access), and – modifying itself so it points to the next element
(called element traversal).There must also be a way: 1./ to create an iterator 2./ to initialize it - so it points to some first element 3./ to determine when the iterator has exhausted all
of the elements in the container.
04/21/23 Assoc. Prof. Stoyan Bonev 34
External Iterators
• Classification:– Implicit iterators (supported in
modern HLL with foreach-like statement)
– Explicit iterators (STL support)
Implicit Iterators
.
04/21/23 Assoc. Prof. Stoyan Bonev 36
Implicit Iterators
Some object-oriented languages such as Perl or Python or C# or VB and later versions of Java provide an intrinsic way of iterating through the elements of a container object without the introduction of an explicit iterator object. This is often manifested by some sort of "for-each“ or "for-in" statement, such as in the following examples:
04/21/23 Assoc. Prof. Stoyan Bonev 37
Implicit Iterators in Perl
# Perl, implicit iterationforeach $val (@list) { print "$val\n";}
Demo program: proba1iterator.pl
04/21/23 Assoc. Prof. Stoyan Bonev 38
04/21/23 Assoc. Prof. Stoyan Bonev 39
Implicit Iterators in Python
# Python, implicit iteration
for Value in List:
print Value
Demo program: proba1iterator.py
04/21/23 Assoc. Prof. Stoyan Bonev 40
04/21/23 Assoc. Prof. Stoyan Bonev 41
Implicit Iterators in Java
// Java, J2SE 5.0, implicit iteration
for (Value v : list)
System.out.print(v);
04/21/23 Assoc. Prof. Stoyan Bonev 42
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList:
for (double value: myList) System.out.println(value);
In general, the syntax is
for (elementType value: arrayRefVar) { // Process the value}
Attention: You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.
04/21/23 Assoc. Prof. Stoyan Bonev 43
Implicit Iterators in Javapublic class ProgForEach {
public static void main(String[] args) { int[] numbers = { 10, 20, 30, 40, 50, 60 }; System.out.println(); for (int element : numbers) { System.out.println(element); }
char[] symbols = { 'a', 'b', 'c', 'A', 'B', 'C' }; System.out.println(); for (char element : symbols) { System.out.println(element); }
String[] strarray = { "BG", "Sofia", "Blagoevgrad", "AUBG" }; System.out.println(); for (String element : strarray) { System.out.println(element); } } // end of main()} // end of main class
04/21/23 Assoc. Prof. Stoyan Bonev 44
Implicit Iterators in C#
Source text: Proba1CSIterator.cs (Class1.cs)
Executable: Proba1CSIterator.exe
04/21/23 Assoc. Prof. Stoyan Bonev 45
namespace ForEach{ class Program { static void Main(string[] args) { Console.WriteLine("Hello, World\n\n");
int[] numbers = { 10, 20, 30, 40, 50, 60 }; Console.WriteLine(); foreach (int element in numbers) { Console.WriteLine(element); }
char[] symbols = { 'a', 'b', 'c', 'A', 'B', 'C' }; Console.WriteLine(); foreach (char element in symbols) { Console.WriteLine(element); }
string[] strarray = { "BG", "Sofia", "Blagoevgrad", "AUBG" }; Console.WriteLine(); foreach (string element in strarray) { Console.WriteLine(element); } Console.ReadLine();
} }}
04/21/23 Assoc. Prof. Stoyan Bonev 46
04/21/23 Assoc. Prof. Stoyan Bonev 47
Implicit Iterators in C++
Source text: STLfor_each.cpp
Executable: STLfor_each.exe
04/21/23 Assoc. Prof. Stoyan Bonev 48
Implicit Iterators in C++
#include <iostream>#include <algorithm>using namespace std;
void InchToSm(double);
void main(){
double inches[] = { 1., 10., 100., 1000. };
for_each(inches, inches+4, InchToSm);}
void InchToSm(double in){
cout << in*2.54 << " ";}
04/21/23 Assoc. Prof. Stoyan Bonev 49
04/21/23 Assoc. Prof. Stoyan Bonev 50
Implicit Iterators in VBasic
• The For Each Statement. It allows you to iterate through all the items in an array (or other collection), examining each item in turn.
• The For Each statement creates a new object that will hold a reference to each in the objects of the collection, in turn, as you loop through the collection.
For Each identifier In collection statementNext
04/21/23 Assoc. Prof. Stoyan Bonev 51
Implicit Iterators in VBasic
Source text: Proba1VBIterator.vb
Executable: Proba1VBIterator.exe
04/21/23 Assoc. Prof. Stoyan Bonev 52
04/21/23 Assoc. Prof. Stoyan Bonev 53
Implicit Iterators in JavaScript
• The For-in Statement. It loops through each of the elements in an array, returning the indexes or keys.
• The number in square brackets is called the index.
• JS arrays support using strings as indexes. When a string is used as an index, this is called a hash table.
04/21/23 Assoc. Prof. Stoyan Bonev 54
Implicit Iterators in JavaScript
var Fruitcolors = new Array(); Fruitcolors[“apples”] = ”red”; Fruitcolors[“bananas”] = ”yellow”; Fruitcolors[“grapes”] = ”purple”;Here, the string “apples” is used as index to store the value
“red”. the string “apples” can be referred to as the key. for (var fruit in FruitColors) {document.write(fruit+” are “+FruitColors[fruit])}
Here, the for-in loop iterates over the document.write() function three times, once for each of the items in the array.
04/21/23 Assoc. Prof. Stoyan Bonev 55
Implicit Iterators in JavaScript
The resulting output is expected to be:
apples are red
bananas are yellow
grapes are purple
Explicit Iterators
.
04/21/23 Assoc. Prof. Stoyan Bonev 57
Explicit Iterators in C++
The C++ language makes wide use of iterators in its Standard Template Library, which provides several different kinds of iterators, including forward iterators, bidirectional iterators, and random access iterators. All of the standard container template types provide a rich and consistent set of iterator types.
The syntax of standard iterators is designed to resemble that of ordinary C pointer arithmetic, where the * and -> operators are used to reference the element to which the iterator points, and pointer arithmetic operators like ++ are used to advance the iterator to the next element.
04/21/23 Assoc. Prof. Stoyan Bonev 58
Explicit Iterators
The iterators are created by the corresponding container class using standard methods such as begin() and end().
The iterator returned by begin() points to the first element.
The iterator returned by end() is a special value that does not reference any element.
When an iterator is advanced beyond the last element it is by definition equal to the special end iterator value.
The following example shows a typical use of an iterator.
ContainerType C; // Any standard container type, like std::list<T>
for (ContainerType::iterator it=C.begin(); it!=C.end(); ++it) { cout << *it << endl; }
STL
- Basic Concepts -.
04/21/23 Assoc. Prof. Stoyan Bonev 60
STL
• STL contains several kinds of entities. The three most important of them are:– Containers– Algorithms– Iterators
04/21/23 Assoc. Prof. Stoyan Bonev 61
STL - Containers
• Creating sequence containers vector<int> aVector, theVector;
list<airtime> departure_list, arrival_list;
• Creating associative containers set<int> intSet;
multiset<employee> machinists;
04/21/23 Assoc. Prof. Stoyan Bonev 62
STL - Iterators
• Iterators are pointer-like entities that are used to access individual data items (called elements) of a container.
• Iterators are used to move sequentially from element to element, a process called iterating through the container.
• Iterators are incremented with ++.• Iterators are used to dereference elements with the *
operator, to obtain the value of the element to which the iterator points.
• In STL iterators are represented by an object of an iterator class.
STL – Demo program illustration of iterators
04/21/23 Assoc. Prof. Stoyan Bonev 64
Standard Template Library
STL: define template class vector of int
oop7Vector1STL.cpp
oop7Vector1STL.exe
04/21/23 Assoc. Prof. Stoyan Bonev 65
04/21/23 Assoc. Prof. Stoyan Bonev 66
STL - Basic Concepts
STL: define iterator for template class vector of int
oop7Vector2STL.cpp
oop7Vector2STL.exe
04/21/23 Assoc. Prof. Stoyan Bonev 67
Exercise Iteration Based on Data Structures
• Build own programs to demonstrate the approach to iterate through all data structure’s elements.
Assignments under discussion are based on lecture 11.
ISBN 0-321-49362-1
Chapter 8
Statement-Level Control Structures
Copyright © 2009 Addison-Wesley. All rights reserved. 1-69Copyright © 2009 Addison-Wesley. All rights reserved. 1-69
Chapter 8 Topics
• Introduction• Selection Statements• Iterative Statements• Unconditional Branching• Guarded Commands• Conclusions
Copyright © 2009 Addison-Wesley. All rights reserved. 1-70Copyright © 2009 Addison-Wesley. All rights reserved. 1-70
Iterative Statements: Iteration Based on Data Structures
• Number of elements of in a data structure control loop iteration
• Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate
• C's for can be used to build a user-defined iterator:for (p=root; p==NULL; traverse(p)){
}
Copyright © 2009 Addison-Wesley. All rights reserved. 1-71Copyright © 2009 Addison-Wesley. All rights reserved. 1-71
Iterative Statements: Iteration Based on Data Structures (continued)
PHP - current points at one element of the array - next moves current to the next element - reset moves current to the first element
• Java - For any collection that implements the Iterator interface - next moves the pointer into the collection - hasNext is a predicate - remove deletes an element
• Perl has a built-in iterator for arrays and hashes, foreach
Copyright © 2009 Addison-Wesley. All rights reserved. 1-72Copyright © 2009 Addison-Wesley. All rights reserved. 1-72
Iterative Statements: Iteration Based on Data Structures (continued)
• Java 5.0 (uses for, although it is called foreach) - For arrays and any other class that implements Iterable interface, e.g., ArrayList
for (String myElement : myList) { … }
• C#’s foreach statement iterates on the elements of arrays and other collections:
Strings[] = strList = {"Bob", "Carol", "Ted"};
foreach (Strings name in strList)Console.WriteLine ("Name: {0}", name);
- The notation {0} indicates the position in the string to be displayed
Copyright © 2009 Addison-Wesley. All rights reserved. 1-73
Iterative Statements: Iteration Based on Data Structures (continued)• Lua
– Lua has two forms of its iterative statement, one like Fortran’s Do, and a more general form:
for variable_1 [, variable_2] in iterator(table) do
…
end
– The most commonly used iterators are pairs and ipairs
Copyright © 2009 Addison-Wesley. All rights reserved. 1-73
Thank YouFor
Your Attention