Ch 9. Templates and Containers Timothy Budd. Ch 9. Templates and Containers2 Introduction A template allows a class or function to be parameterized by.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Quick Overview of STL STL = Standard Template Library Main concept : Container, Iterator Application : Linked list, Stack etc.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
C++ for Engineers and Scientists Third Edition
1 ES 314 Advanced Programming Lec 2 Sept 3 Goals: Complete the discussion of problem Review of C++ Object-oriented design Arrays and pointers.
Data Structures Data structures permit the storage of related data for use in your program. –Arrays.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
Object Oriented Data Structures
Ch 7. Operator Overloading Timothy Budd. Ch 7. Operator Overloading2 Introduction Almost all operators in C++ can be overloaded with new meanings. Operators.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Containers Overview and Class Vector
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import.
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
C++ STL CSCI 3110.
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.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
The Standard Template Library Container Classes Version 1.0.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
C19: Collection Classes (don’t forget to look at all the online code examples)
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
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.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
Standard Template Library
Introduction to Custom Templates
Standard Template Library (STL)
Pointers and References
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Standard Template Library
Chapter 3 Lists, Stacks, and Queues
SPL – PS1 Introduction to C++.
Presentation transcript:

Ch 9. Templates and Containers Timothy Budd

Ch 9. Templates and Containers2 Introduction A template allows a class or function to be parameterized by a type. The template mechanism is performed at compile time, permits extensive type checking statically, and eliminates many of the run-time casts that typically populate Java programs. Use of template: a major tool to develop a rich set of data structure, container, or abstractions.

Ch 9. Templates and Containers3 Template Classes template class box { public: box ( ) { } box (T v) : val(v) { } box (box & right) : val(right.val) { } T value() { return val; } void operator = (T right) { val = right; } void operator = (box & right) { val=right.val; } private: T val; };

Ch 9. Templates and Containers4 Template Classes A class template gives the programmer the ability to define a data type in which some type information is purposely left unspecified - to be field in at a later time. The class definition has been parameterized in a manner similar to a procedure or function. Different instantiation of a parameterized class can fill in the type information in different ways.

Ch 9. Templates and Containers5 Template Classes box ib; box db; ib = 7; db = 3.14; box ibtwo = 4; // can be initialized in constructor ib = ibtwo; int x = ib.value(); ib = 2.7; // error - cannot assign real to int

Ch 9. Templates and Containers6 Template Classes The most common use for template classes is to create container class. list ilist;// create a list of integers list dlist:// create a list of real numbers list alist;// create a list of pointers to animals ilist.push_front(7);// add an element to front of list int x = ilist.front(); // extract first element from list

Ch 9. Templates and Containers7 Template Classes Two main problems with Java approach: –Non-object values, such as primitive types, cannot be stored in Java collections. (c.f. wrapper class, Integer) –When a value is removed, it must be cast back to the appropriate type. With templates, the C++ allows creation and manipulation of truly reusable, general purpose components with a minimum of difficulty but retention of type safety. On the other hand, Java can easily maintain heterogeneous collection, that is, collections of values of various types.

Ch 9. Templates and Containers8 template class bitSet { public: set (int index) {... } test (int index) {... } void operator = (bitSet & right); protected: // assume 16 bits per word int data [ (s + 15)/ 16 ]; };

Ch 9. Templates and Containers9 bitSet a; a.set(17); // set position 17 if (a.test(i))... bitSet b; bitSet c; a = b; // ok, will execute assignment operator a = c; // produces compile time error, sizes don't match

Ch 9. Templates and Containers10 Template Methods When template methods are written separately from the class definition, they must also be parameterized by the template argument: template void bitSet ::operator = (bitSet & right) { // first compute the data vector size int max = (s + 15) / 16; // then copy all the data fields into our array for (int i = 0; i < max; i++) data[i] = right.data[i]; }

Ch 9. Templates and Containers11 Template Function Ordinary functions can also be given template definitions. template T max (T left, T right) { // return largest value if (left < right) return right; else return left; }

Ch 9. Templates and Containers12 Template function types will be inferred from the argument values and need not be specified by the programmer. int i = max(3, 4); double d = max(3.14, 4.7); // assume comparison has been defined for class anObject AnObject a, b; AnObject c = max(a, b); // mixing types will not work int i = max(2, a); // will produce compiler error

Ch 9. Templates and Containers13 Template Functions Errors in template functions are often difficult to trace back to the originating statement.

Ch 9. Templates and Containers14 The Standard Template Library The Standard Template Library (STL) is a collection of useful container classes for common data structures. VectorResizeable array list Linked list DequeDouble ended vector set and multisetOrdered set map and multimapKeyed dictionary StackLast-in, first out collection QueueFirst-in, first out collection priority queueOrdered access collection

Ch 9. Templates and Containers15 The Standard Template Library Interator is a generalization of a memory pointer, used to access elements in a container without knowledge of the internal representation for the container, similar to the class Enumeration in Java.

Ch 9. Templates and Containers16 Containers Vectors: class vector represents a dynamically resizable array. –Unlike Java, the C++ class must be provided with a template parameter that describes the element type: vector a; vector b(10); // initially ten elements –Like arrays and strings, vectors in C++ do not check for out-of-range index values.

Ch 9. Templates and Containers17 Table 9.1 Comparison of Vector Methods OperationC++Java Creationvector v; vector v(int size); vector v(size, initial value); vector v(oldvector); v = new Vector(); Element accessv[index]elementAt(index) First element Last element front() back() fistElement() lastElement() Size Empty test size() empty() resize(newsize) capacity() reserve(newsize) size() isEmpty() setSize(newsize) capacity() ensureCapacity(newsize) Add to front Add to back Insert at position Change at position push_front(value) push_back(value) insert(interator, value) v[position] = value insertElementAt(value, 0) addElement(value) insertElementAt(value, position) setElementAt(value, position) Remove last element Remove from position pop_back() erase(iterator) None removeElementAt(position) Copyvector v(oldvector);Clone() Create iteratorbegin() end() Elements()

Ch 9. Templates and Containers18 Containers Linked list –Allow insertions and removals from both the front and back of the container. –Insertion and removals from the middle are performed in constant time rather than the O(n) time required by the vector data type. A list Link

Ch 9. Templates and Containers19 Deque –Can be thought of as a pair of vectors placed back to back, moving opposite directions. –Permits efficient (constant time) insertion at either end but slower linear insertion in the middle. –More space-efficient structure than a list.

Ch 9. Templates and Containers20 Set –Maintains elements in order and thereby permits very efficient time insertion, removal, and inclusion tests for values. –Internally implemented by a balanced binary tree.

Ch 9. Templates and Containers21 Map –An indexed collection, similar to the Java Dictionary or Harshtable. –Parameterized by two template arguments, key type and value type. –Operations are implemented with a data type called a pair, which is a key/value combination.

Ch 9. Templates and Containers22 Stack and Queue –In STL, they are adapters, built on top of an underlying data type such as a vector or linked list. –Adapter: a software component that changes the interface to another component stack > stackOne; stack > stackTwo; queue > queueOne

Ch 9. Templates and Containers23 Priority Queue –Built as an adaptor on top of another container, typically a vector or a list. –Two template arguments are used with a priority queue: underlying container and a function object that is used to compare elements.

Ch 9. Templates and Containers24 Iterators The concept of an iterator in the STL is similar to Enumeration in Java but differs in the particulars of use.

Ch 9. Templates and Containers25 Example of Iterators int sum = 0; for (Enumeration e = v.elements();e.hasMoreElements(); ) { Object val = e.nextElement(); Integer iv = (Integer) val; sum += iv.intValue(); } int sum = 0; vector ::iterator start = v.begin(); vector ::iterator stop = v.end(); for ( ; start != stop; ++start) sum += *start;

Ch 9. Templates and Containers26 Iterators Not need to cast the object to the proper type after it has been removed from the container. Containers can store primitive types and do not need the wrapper class necessitated by the Java version. To create an iterator, first requires specifying the container type. Iterators must be manipulated in pairs with a beginning and an ending iterator.

Ch 9. Templates and Containers27 Iterators Designed to be equivalent – and compatible with – conventional pointers. Can be used to denote a specific vale. A pair of iterators can be used to describe a range of values.

Ch 9. Templates and Containers28 Iterators card[0]card[51]card[50]…..card[2]card[1]

Ch 9. Templates and Containers29 Iterators Iterators produced by containers often come in pairs. The beginning iterator is returned by the function begin, and the ending iterator by the function end.

Ch 9. Templates and Containers30 template iterator find (iterator first, iterator last, T & value) { while (first != last && *first != value) ++first; return first; } int data[100];... int * where = find(data, data+100, 7); list ::iterator where = find(aList.begin(), aList.end(), 7);

Ch 9. Templates and Containers31 Iterator Three requirements for an iterator: –Can be compared for equality to another iterator. Equal when they point to the same position but otherwise are not equal. –Can be dereferenced with the * operator to obtain the value being denoted by the iterator. Can be used as the target of an assignment in order to change the value being held by the container. –Can be incremented so that it refers to the next element in sequence, using the operator ++.

Ch 9. Templates and Containers32 Generic Algorithms Generic algorithm: a software algorithm that can be used with many different collection classes. random_shuffle (cards, cards+52, randomizer);

Ch 9. Templates and Containers33 Function Objects Function object: an object that can be uesd in the fashion of a function. class randomInteger { public: unsigned int operator () (unsigned int max) { // compute rand value between 0 and max unsigned int rval = rand(); return rval % max; } }; randomInteger randomizer; // create an instance of class

Ch 9. Templates and Containers34 Function Objects class LargerThan { public: // constructor LargerThan (int v) { val = v; } // the function call operator bool operator () (int test) { return test > val; } private: int val; }; LargerThan tester(12); // create the predicate function list ::iterator found = find_if (aList.begin(), aList.end(), tester); if (found != aList.end()) printf("element is %d", *found); // found such a value else printf("no element larger than 12");

Ch 9. Templates and Containers35 LargerThan(12) // creates an instance of LargerThan list ::iterator found = find_if (aList.begin(), aList.end(), LargerThan(12)); class charCompare { // compare two character literal values public: bool operator () (const char * left, const char * right) const { return strcmp(left, right) < 0; } }; typedef map cityInfo;