11 COS220 Concepts of PLs AUBG, COS dept Lecture 36 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++, Lafore, Chap 15 STL,

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
True or false A variable of type char can hold the value 301. ( F )
Chapter 10.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CS Oct 2006 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
C++ for Engineers and Scientists Third Edition
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Templates and the STL.
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
Object Oriented Data Structures
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Data Structures Using C++ 2E
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Object Oriented Programming Elhanan Borenstein Lecture #11 copyrights © Elhanan Borenstein.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan Snd Term Nouf Aljaffan (C) CSC 1201 Course at KSU1.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 14 Introduction to Sorting Algorithms Jeffrey S. Childs Clarion University of PA © 2008, Prentice.
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
An Introduction to STL. The C++ Standard Template Libraries  In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a.
C++ Lecture 1 Friday, 4 July History of C++ l Built on top of C l C was developed in early 70s from B and BCPL l Object oriented programming paradigm.
Chapter 11 Hash Tables © John Urrutia 2014, All Rights Reserved1.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
1 CSC241: Object Oriented Programming Lecture No 25.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Starting Out with C++, 3 rd Edition Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Lecture 7-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Lecture 36 OOP The STL Standard Template Library
Motivation for Generic Programming in C++
Dr. Bernard Chen Ph.D. University of Central Arkansas
Collections Intro What is the STL? Templates, collections, & iterators
18 – Sequential Containers
Chapter 22: Standard Template Library (STL)
Engineering Problem Solving with C++, Etter
Fundamental Programming
Presentation transcript:

11 COS220 Concepts of PLs AUBG, COS dept Lecture 36 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++, Lafore, Chap 15 STL, pp

2. Lecture Title: STL – Algorithms sources: R.Lafore, OOP In C++, Chap 15 STL, pp

3 Lecture contents: §STL – overview §STL – structure and components l Sequence Containers l Algorithms l Associative Containers l Iterators §Practical session

STL - Basic Concepts -.

5 STL §STL contains several kinds of entities. The three most important of them are: l Containers Sequence containers Associative containers l Algorithms l Iterators

6 STL Containers: §A Container is a way that stored data is organized in memory. §Common containers: l Stack, List, Queue. l Array (most common that built-in to all PL). §STL containers are implemented by template classes, so they may be customized to contain different kinds of data.

7 STL Algorithms: §Algorithms are Procedures that are applied on containers to process their data in various ways. §Algorithms to sort, copy, search, merge data. §Algorithms are represented by stand alone template functions (not members of container classes). §Algorithms are so general that can be used not only on STL containers but also on ordinary C++ arrays and on user-specified containers.

8 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 as key parts of STL, because they connect algorithms with containers. See next slide.

9

10 STL Algorithms

11 STL - Algorithms §An Algorithm is a function that does something to the items of a container or to a set of containers. §STL algorithms are not member functions or even friends of container classes which was typical for early class libraries. §STL Algorithms are represented by stand alone template functions (not members of container classes). §STL Algorithms are so general that can be used not only on STL containers but also on ordinary C++ arrays and on user-specified containers.

12 Typical STL - Algorithms find() returns first element equivalent to a specified value. count() counts the number of elements that have a specified value. equal() compares the contents of two containers and returns true if all corresponding elements are equal. search() looks for a sequence of values in one container that corresponds with the same sequence in another container. copy() copies a sequence of values from one container to another (or to a different location in the same container). swap() exchanges a value in one location with a value in another. iter_swap() exchanges a sequence of values in one location with a sequence of values in another location. fill() copies a value into a sequence of locations. sort() sorts the values in a container according a specified ordering. merge() combines two sorted ranges of elements to make a larger sorted range. accumulate() returns the sum of the elements in a given range. for_each() executes a specified function for each element in a container. Full list of algorithms – See R.Lafore book, Appendix F

13 STL – Algorithms How to proceed?  Suppose you create an int array with data in it: int arr[8] = {42, 31, 7, 80, 2, 26, 19, 75 };  You can sort the array using the sort() algorithm sort(arr, arr+8); Where arr is the address of the array beginning arr+8 is the past-the-end address (one item past the end of the array).  STL Advantage: You can use the same context with array of other type like float, double etc.

14 STL - Algorithms §All STL algorithms need header file #include

15 STL – The find() Algorithm  The find() algorithm looks for the first element in a container that has a specified value. §Example: int arr[] = { 11, 22, 33, 44, 55, 66, 77, 88 };... int* ptr; ptr = find(arr, arr+8, 33); §See file Ch15\Find.cpp

16 STL – The find() Algorithm // find.cpp // finds the first object with a specified value #include #include //for find() using namespace std; int arr[] = { 11, 22, 33, 44, 55, 66, 77, 88 }; int main() { int* ptr; ptr = find(arr, arr+8, 33); //find first 33 cout << "First object with value 33 found at offset " << (ptr-arr) << endl; return 0; }

17 Ranges §The first two parameters specify the range of elements to be examined. These values are specified by iterators. We use normal C++ pointer values, which are a special case of iterators. §The first parameter is the iterator of (or the pointer to) the first value to be examined. §The second parameter is the iterator of the location one past the last element to be examined (past-the-end value). It points to the element just past the end of the range to be examined. See previous slide.

18 Final remarks on find() algorithm ptr = find(arr, arr+8, 33); §The statement above is reminiscent of the normal C++ idiom in a for loop: for (int j=0; j<8; j++) { if (arr[j] == 33) { cout << “Element 33 found at offset” << j; break; } §The find() algorithm saves the trouble of writing explicit loop as it is shown above. This consideration is valid for all STL algorithms.

19 STL – The count() Algorithm §The count() algorithm counts how many elements in a container have a specified value and returns this number. §Example: int arr[] = { 33, 22, 33, 44, 33, 55, 66, 77 };... int n = count(arr, arr+8, 33); //count num of 33's §See file Ch15\Count.cpp

20 STL – The count() Algorithm // count.cpp // counts the number of objects with a specified value #include #include //for count() using namespace std; int arr[] = { 33, 22, 33, 44, 33, 55, 66, 77 }; int main() { int n = count(arr, arr+8, 33); //count number of 33's cout << "There are " << n << " 33's in arr." << endl; return 0; }

21 STL – The sort() Algorithm §The sort() algorithm sorts in ascending order the elements of a container. §Example: int arr[] = {45, 2, 22, -17, 0, -30, 25, 55};... sort(arr, arr+8);// sort the numbers §See file Ch15\Sort.cpp

22 STL – The sort() Algorithm // sort.cpp // sorts an array of integers #include using namespace std; // array of numbers int arr[] = {45, 2, 22, -17, 0, -30, 25, 55}; int main() { sort(arr, arr+8); // sort the numbers for(int j=0; j<8; j++) // display sorted array cout << arr[j] << ' '; cout << endl; return 0; }

23 STL – The search() Algorithm §Some algorithms operate on two containers at once. While the find() algorithm looks for a specified value in a single container, the search() algorithm looks for a sequence of values, specified by one container, within another container. §See file Ch15\Search.cpp. Example : int source[] = { 11, 44, 33, 11, 22, 33, 11, 22, 44 }; int pattern[] = { 11, 22, 33 };... int* ptr; ptr = search(source, source+9, pattern, pattern+3); if(ptr == source+9) // if past-the-end cout << "No match found\n"; else cout << "Match at " << (ptr - source) << endl;

24 STL – The search() Algorithm // search.cpp // searches one container for a sequence in another container #include using namespace std; int source[] = { 11, 44, 33, 11, 22, 33, 11, 22, 44 }; int pattern[] = { 11, 22, 33 }; int main() { int* ptr; ptr = search(source, source+9, pattern, pattern+3); if(ptr == source+9) // if past-the-end cout << "No match found\n"; else cout << "Match at " << (ptr - source) << endl; return 0; }

25 STL – The merge() Algorithm §The merge() algorithm works with three containers, merging the elements from two source containers into a destination container. §See file Ch15\Search.cpp. Example : int src1[] = { 2, 3, 4, 6, 8 }; int src2[] = { 1, 3, 5 }; int dest[8];... merge(src1, src1+5, src2, src2+3, dest);

26 STL – The merge() Algorithm // merge.cpp // merges two containers into a third #include #include //for merge() using namespace std; int src1[] = { 2, 3, 4, 6, 8 }; int src2[] = { 1, 3, 5 }; int dest[8]; int main() { //merge src1 and src2 into dest merge(src1, src1+5, src2, src2+3, dest); for(int j=0; j<8; j++) // display dest cout << dest[j] << ' '; cout << endl; return 0; }

27 STL – Function objects §Some algorithms can take function object as an argument. A function object looks to the user like a template function. However, it’s an object of a template class that has a single member function: the overloaded () operator.  The sort() algorithm usually sorts in ascending order, but the use of the function object greater<>() as a third argument of the sort() algorithm reverses the sorting order. §See next slide

28 STL – Function objects, modified sort() algorithm §Besides comparisons, there are function objects for arithmetical and logical operators. §See file Ch15\Sortemp.cpp. Example : #include //for sort() #include //for greater<>... double fdata[] = { 19.2, 87.4, 33.6, 55.0, 11.5, 42.2 }; sort( fdata, fdata+6, greater () ); sort( fdata, fdata+6);

29 STL – Function objects, modified sort() algorithm // sortemp.cpp // sorts array of doubles in backwards order, // uses greater<>() function object #include #include //for sort() #include //for greater<> using namespace std; // array of doubles double fdata[] = { 19.2, 87.4, 33.6, 55.0, 11.5, 42.2 }; int main() { // sort the doubles sort( fdata, fdata+6, greater () ); for(int j=0; j<6; j++) // display sorted doubles cout << fdata[j] << ' '; cout << endl; return 0; }

30 User-written Functions in Place of Function Objects Function objects operate only on basic C++ types and on classes for which appropriate operators are defined. If you are working with values for which this is not the case, you can or you have to substitute a user-written function to a function object. For example, the operator < is not defined for char* strings, but we can write a function to perform the < comparison, and use the function’s address (its name) in place of the function object. See next slide.

31 User-written Functions in Place of Function Objects // sortcom.cpp // sorts array of strings with user-written comparison function #include #include // for strcmp() #include using namespace std; // array of strings char* names[] = { "George", "Penny", "Estelle", "Don", "Mike", "Bob" }; bool alpha_comp(char*, char*); // declaration int main() { sort(names, names+6, alpha_comp); // sort the strings for(int j=0; j<6; j++) // display sorted strings cout << names[j] << endl; return 0; } bool alpha_comp(char* s1, char* s2) // returns true if s1<s2 { return ( strcmp(s1, s2)<0 ) ? true : false; }

32 User-written Functions in Place of Function Objects The third argument to the sort() algorithm is the address of the alpha_comp() function which compares two char* strings and returns true or false depending on whether the first is lexicographically less than the second. sort(names, names+6, alpha_comp); // sort the strings... bool alpha_comp(char* s1, char* s2) // returns true if s1<s2 { return ( strcmp(s1, s2)<0 ) ? true : false; } Actually you don’t need to write your own function objects to handle text. In STL if you use the string class, you can use built-in function objects such as less<>() and greater<>()

33 STL – Adding _if to Algorithms  Some algorithms end in _if. They take an extra predicate parameter, which is a function object or a function. The example uses string objects. The find_if() algorithm is supplied with a user-written isDon() function to find the first string in an array of string objects that has the value “Don”. §See file Ch15\Find_if.cpp. Example: bool isDon(string name) { return name == "Don"; } string names[] = { "George", "Estelle", "Don", "Mike", "Bob" };... string* ptr; ptr = find_if( names, names+5, isDon ); if(ptr==names+5) cout << "Don is not on the list.\n"; else cout << "Don is element " << (ptr-names) << " on the list.\n";

34 STL – Adding _if to Algorithms // find_if.cpp // searches array of strings for first name that matches "Don" #include using namespace std; // bool isDon(string name) { return name == "Don"; } // returns true if name=="Don" // string names[] = { "George", "Estelle", "Don", "Mike", "Bob" }; int main() { string* ptr; ptr = find_if( names, names+5, isDon ); if(ptr==names+5) cout << "Don is not on the list.\n"; else cout << "Don is element " << (ptr-names) << " on the list.\n"; return 0; }

35 STL – The for_each() Algorithm §The for_each() algorithm allows to do something to every item in a container. You write your own function to describe that “something”. Your function can’t change the elements in the container but it can use or display their values. §See file Ch15\For_each.cpp. Example : void in_to_cm(double); // declaration... double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; for_each(inches, inches+5, in_to_cm); // output as cms... void in_to_cm(double in) // convert and display as cms { cout << (in * 2.54) << ' '; }

36 STL – The for_each() Algorithm // for_each.cpp // uses for_each() to output inches array elements as centimeters #include using namespace std; void in_to_cm(double); // declaration int main() { // array of inches values double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; // output as centimeters for_each(inches, inches+5, in_to_cm); cout << endl; return 0; } void in_to_cm(double in) // convert and display as centimeters { cout << (in * 2.54) << ' '; }

37 STL – The transform() Algorithm  The transform() algorithm does something to every item in a container and places the resulting values in a different container (or the same one). You write your own function to describe that “something”. Your function return type must be the same as that of the destination container. §See file Ch15\Transfo.cpp. Example : double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; double centi[5]; double in_to_cm(double);// prototype // transform into array centi[] transform(inches, inches+5, centi, in_to_cm);... double in_to_cm(double in)// convert inches to centimeters { return (in * 2.54);// return result }

38 STL – The transform() Algorithm // transfo.cpp // uses transform() to change array of inches values to cm #include using namespace std; int main() { // array of inches values double inches[] = { 3.5, 6.2, 1.0, 12.75, 4.33 }; double centi[5]; double in_to_cm(double); // prototype // transform into array centi[] transform(inches, inches+5, centi, in_to_cm); for(int j=0; j<5; j++) // display array centi[] cout << centi[j] << ' '; cout << endl; return 0; } double in_to_cm(double in) // convert inches to centimeters { return (in * 2.54); // return result }

39 Algorithms and Iterators §Algorithms use iterators as arguments and sometimes as return values. §Demo; the find() algorithm applied to a list l List of integers 2, 4, 6, 8, 10 l Next slide: Find looks for data item 8 and answers Yes or No

40 Algorithms and Iterators §First; to create a container and iterator list theList(5); // empty list holds 5 ints list ::iterator it; §Second: to populate the container using iterator int data = 0; for( it=theList.begin(); it!=theList.end(); it++) *it = data += 2;// 2, 4, 6, 8, 10 §Third: Call find(), looking for data item 8 it=find(theList.begin(), thelist.end(), 8); if (it != theList.end() ) cout << “\n Found data item 8”; Else cout << “\n did not find 8”;

41 Algorithms and Iterators §Algorithms use iterators as arguments and sometimes as return values. §Demo; the find() algorithm applied to a list l List of integers 2, 4, 6, 8, 10 l Next slide: Find looks for data item 8 and answers Yes or No, followed by the location where data item was found

42 Algorithms and Iterators §First; to create a container and iterator list theList(5); // empty list holds 5 ints list ::iterator it; §Second: to populate the container using iterator int data = 0; for( it=theList.begin(); it!=theList.end(); it++) *it = data += 2;// 2, 4, 6, 8, 10 §Third: Call find(), looking for data item 8 it=find(theList.begin(), thelist.end(), 8); if (it != theList.end() ) cout << “\n Found data item 8 at location ” << (it – theList.begin() ); Else cout << “\n did not find 8”;

43 Thank You for Your Attention! Any Questions?