1 / 82

COS220 Concepts of PLs AUBG, COS dept

COS220 Concepts of PLs AUBG, COS dept. Lecture 37 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++ , Lafore, Chap 15 STL, pp 726-797. 1. Lecture Title: Iteration Based on Data Structures and STL – Iterators

louvain
Download Presentation

COS220 Concepts of PLs AUBG, COS dept

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COS220 Concepts of PLs AUBG, COS dept Lecture 37 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++ , Lafore, Chap 15 STL, pp 726-797 1

  2. . Lecture Title: Iteration Based on Data Structures and STL – Iterators sources: R.Lafore, OOP In C++, Chap 15 STL, pp 726-797 http://www.sgi.com/tech/stl/ http://en.wikipedia.org/wiki/Standard_Template_Library

  3. Lecture contents: • Introducing the concept of iterating through data_structure elements • Internal iterator • External iterator • Implicit iterator • Explicit iterator (supported by STL) • Examples

  4. OOP Iteration Based on Data Structures

  5. Iteration that depends on data structures: Rather than having an index variable and Counter Controlled LOOP or a boolean expression and Logically Controlled LOOP to dictate the number of iterations, we have LOOPS whose iterations depend on the current number of data items /elements/ within the data structure /container/.

  6. The rule: • Data based iteration statement uses an abstract defined data structure and a member function to go through the structure’s elements. Such a function is called an internaliterator. • External iterator – a pointer-like type that references elements of a container and which is used to navigate through a container object.

  7. Data structure Function Borland Container Class Library Internal Iterator, three member functions List forEach() actionFunc() Queue firstThat() testFunc() lastThat() STL Standard Template Library External Iterator 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;

  8. Abstract Data TypesForDynamic Data Structures: List, Queue

  9. CCLClass Hierarchy &Selected Classes

  10. CCL – class hierarchy Object | \ \ \ Sortable Association Container Error

  11. CCL – class hierarchy Container | \ \ \ Collection Stack Queue Deque | \ \ \ AbstractArray List DoubleList HashTable / \ | Array SortedArray Bag Set Dictionary

  12. List in CCL 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. 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

  13. Queue in CCL • Queue – items in at end of queue, items out at the other end on FIFO basis. CCL: the Queue class (#include <queue.h>) Methods: put() – add object to head of queue get() – remove object from tail of queue peekLeft() – examine object at head of queue peekRight() – examine object at tail of queue

  14. Container in CCL CCL: the Container class Methods: firstThat() – find first object satisfying condition lastThat() – find last object satisfying condition

  15. Internal Iterators

  16. 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(). • Instead of using a counter variable or a boolean expression to control the number of iterations, these loops use the number of elements in abstract defined data structure. • 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.

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

  18. Container Class Library CCL: the List class: method forEach() oop7a.cpp oop7a.exe

  19. Container Class Library First: 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; }

  20. Container Class Library CCL: the List class: methods firstThat(), lastThat() oop7ba.cpp oop7ba.exe

  21. Container Class Library First: 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"); }

  22. Container Class Library First: 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"); }

  23. From List to Queue .

  24. Container Class Library CCL: the Queue class: methods forEach(), firstThat(), lastThat() oop7bb.cpp oop7bb.exe

  25. 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, 2014); Date * pd2 = new Date(2, 15, 2014); Date * pd3 = new Date(3, 20, 2014); Date * pd4 = new Date(4, 25, 2014); q.put(*pd1); // put four dates to the queue q q.put(*pd2); q.put(*pd3); q.put(*pd4);

  26. 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; }

  27. External Iterators

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

  29. External Iterators • Classification: • Implicit iterators (supported in modern HLL with foreach-like stmt) • Explicit iterators (STL support)

  30. Implicit Iterators .

  31. Implicit Iterators Some object-oriented languages such as Perl or Python or C# or VB or 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" statement, such as in the following examples:

  32. Implicit Iterators in Perl # Perl, implicit iteration foreach $val (@list) { print "$val\n"; } Demo program: proba1iterator.pl

  33. Implicit Iterators in Python # Python, implicit iteration for Value in List: print Value Demo program: proba1iterator.py

  34. Implicit Iterators in Java // Java, J2SE 5.0, implicit iteration for (Value v : list) System.out.print(v);

  35. Implicit Iterators in C# Source text: Proba1CSIterator.cs (Class1.cs) Executable: Proba1CSIterator.exe

  36. 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 EachidentifierIncollection statement Next

  37. Implicit Iterators in VBasic Source text: Proba1VBIterator.vb Executable: Proba1VBIterator.exe

  38. Implicit Iterators in C++ Source text: STLfor_each.cpp Executable: STLfor_each.exe

  39. 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 << " "; }

  40. Explicit Iterators .

  41. STLIterators

  42. STL Iterators: • Generalization of the concept of pointers. They point to element in Container. • Iterator may increment, so it points in turn to each element in Container. • Iterators are a key part of the STL because they connect algorithms with containers. Think of them as a software version of cables, like the cables that connect stereo components together or a computer to its peripherals.

  43. 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. • You can increment iterators with the ++ operator so they point to the next element, and dereference them with the * operator to obtain the value of the element they point to. • In the STL iterators are represented by an object of an iterator class.

  44. STL - Iterators • Different classes of iterators must use with different types of container. Three major classes: • Forward iterator – can move only forward through the container, one item at a time; • Bidirectional iterator – can move backward as well as forward; • Random access iterator – in addition to moving forward and backward can jump to an arbitrary location; • Input iterator – can “point to” an input device (cin or file) to read sequential data items into a container; • Output iterator – can “point to” an output device (cout or file) to write elements from a container to the device.

  45. STL - Iterators • Forward iterator • A forward iteratorcan only move forward through the container, one item at a time using its ++ operator. It can’t move backward and it can’t be set to an arbitrary location in the middle of the container.

  46. STL - Iterators • bi-directional iterator • A bidirectional iteratorcan move backward as well as forward, so both its ++ and -- operators are defined.

  47. STL - Iterators • random access iterator • A random access iterator, in addition to moving backward and forward, can jump to an arbitrary location. You can tell it to access location 27, for example.

  48. STL - Iterators • There are also two specialized kinds of iterators. • An input iteratorcan “point to” an input device (cin or a file) to read sequential data items into a container. • An output iteratorcan “point to” an output device (cout or a file) and write elements from a container to the device.

  49. STL - Iterators • While the values of forward, bi-directional, and random access iterators can be stored (so they can be used later), the values of input and output iterators cannot be. • This makes sense: the first three iterators point to memory locations, while input and output iterators point to I/O devices for which stored “pointer” values have no meaning.

More Related