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.

Slides:



Advertisements
Similar presentations
M The University Of Michigan Andrew M. Morgan EECS Lecture 22 Savitch Ch. 16 Intro To Standard Template Library STL Container Classes STL Iterators.
Advertisements

SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Data Structures Using C++ 2E
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
The Assembly Language Level
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Object Oriented Programming Elhanan Borenstein Lecture #12 copyrights © Elhanan Borenstein.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Standard Containers: Vectors
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
More on the STL vector list stack queue priority_queue.
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)
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Templates and the STL.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
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
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,
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
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)
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
C++ STL CSCI 3110.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
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.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
Chapter 22 STL Containers §22.1 STL Basics §22.2 STL Iterators §22.3 Sequence Containers §22.4 Associative Containers §22.5 Container Adapters.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Templates&STL. Computer Programming II 2 Introduction They perform appropriate operations depending on the data type of the parameters passed to them.
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)
Intro to the C++ STL Timmie Smith September 6, 2001.
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
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.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
C++ Review STL CONTAINERS.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
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.
Object-Oriented Programming (OOP) Lecture No. 41
Standard Template Library
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library (STL)
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 22: Standard Template Library (STL)
CS212: Object Oriented Analysis and Design
Iterators and STL Containers
Exceptions, Templates, and the Standard Template Library (STL)
Standard Template Library
Standard Template Library
Standard Template Library
Presentation transcript:

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 the same for data of any type.  Templates provide:  Provide a mechanism to implement the concept of generic programming.  Allows programmers to create a family of similar classes or functions.  Eliminates code duplication for different types and thus make the software development easier and more manageable.  Are to be defined with parameters that would be replaced by a specified data type at the time of actual use of the class or function.

Two types  function templates special functions that can operate with generic types.  class templates can have members that use template parameters as types

 template  return-type function-name (arguments of type T)  {  //Body of the function with type T  }

template return-type function-name (arguments of types T1, T2,...) { //Body of the function with types T1, T2, etc., }

 #include  template  T max(T a, T b)  {  return a > b ? a : b ;  }  int main()  {  cout << "max(10, 20) = " << max(10, 20) << endl ;  cout << "max('k', 'u') = " << max('k', 'u') << endl ;  cout << "max(111.41, ) = " << max(111.41, ) << endl ;  return 0;  }

 A class template definition looks like a regular class definition, except it is prefixed by the keyword template. This prefix tells the compiler that we are going to declare a template and use T as a type name in the declaration.  template  class classname  {  //Body of the class  };

 Exceptions are errors that occur at run-time. An Exceptional condition is an event that occurs during the execution of C++ program (runtime anomalies) causing a program to interrupt.  Examples: Out-of-bound array subscript, arithmetic overflow or underflow, division by zero, or Hardware Interupts.

 try  { ...  if(condition)  {  throw an_exception;  }  catch ( an_exception)  {  //Exception Handling Statements  }

 The STL is a collection of generic classes and functions that provides solutions to manage data with modern and efficient algorithms.  Advantages of STL  You don't have to write your classes and algorithms. It saves your time.  You don't have to worry about allocating and freeing memory.  Reduces your code size because STL uses templates to develop these classes.  Easy to use and easy to learn.

 STL contain several components. The three key components are as below:  Containers : A container is a way that stored data is organized in memory.  Algorithms : Algorithms in STL are procedures that are applied to containers to process their data in various ways.  Iterators : Iterators are a generalization of the concept of pointers: they point to elements in pointers.

 It is a way to store data, whether the data is of built-in types or of class objects. The STL containers are implemented by template classes, so they can be easily customized to hold different kinds of data. STL defines ten containers grouped in three categories as below

 Sequence containers ▪ Vector(arrays that can change its size) ▪ Deque(Double ended queue) ▪ list  Associative containers ▪ Set ▪ Multiset ▪ Map ▪ Multimap  Derived containers ▪ Stack ▪ Queue ▪ Priority queue

ContainerCharacteristicsAdvantages and disadvantages Ordinary C++ array Fixed size Quick random access(by index number) Slow to insert or erase in the middle Size cannot be changed at runtime Vector Relocating, expandable array Quick random access(by index number) Slow to insert or erase in the middle Quick to insert or erase at end List Doubly linked list Quick to insert or delete at any location Quick access to both ends Slow random access Deque Like vector, but can be accessed at either ends Quick random access(by index number) Slow to insert or erase in the middle Quick insert or erase (push and pop) at either the beginning or the end

 Sorted collections in which the actual position of an element depends on its value due to a certain sorting criteria. It supports direct access to elements using keys.There are four types of associative containers:  Set  Multiset  Map  Multimap  All these containers store data in a structure called tree which facilitates fast searching, deletion and insertion. However they are slow for random access and inefficient for sorting.

ContainerCharacteristics Set Stores only the key objects Only one key of each value allowed Multiset Stores only the key objects Multiple key values allowed Map Associates key object with value object Only one key of each value allowed Multimap Associates key object with value object Multiple key values allowed The below summarizes the characteristics of associative containers in STL.

 Collection where elements are sorted according to their own values. Each element may occur only once.  Elements of a set are automatically sorted when an element is inserted/deleted.  Sets do not provide operations for direct element access.

 Same as set, except that duplicates are allowed

 Contains elements that are key/value pairs. Each element has a key that is the basis for the sorting criterion and a value. Each key may occur only once (duplicate keys not allowed)

 Same as a map, except that duplicates are allowed. (multiple elements may have the same key)

ContainerImplementationCharacteristics Stack Can be implemented as Vector, list or deque Insert (push) and remove(pop) at one end only Queue Can be implemented as listor deque Insert (push) at one end,remove (pop) at other Priority_Queu e Can be implemented as vector or deque Insert(push) in random order at one end, remove (pop) insorted order from other end

 Elements come in order of importance (stored ranked elements and highest ranked ones are removed first)  Generally made out of vector. 2 I/O Error 0 Normal 5 Interrupt 2 I/O Error0 Normal 5 Interrupt

 Algorithms are functions for processing the elements of a container. These functions are not member functions of container classes, rather they are standalone functions i.e the algorithms are general. Hence they can be used, not only on STL containers, but on ordinary C++ arrays and on containers you create yourself.

AlgorithmPurpose 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 correspond 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 to 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 the container

 Iterators are pointer-like entities that are used to access individual data items (which are usually called elements), in a container.  Often they 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 an iterator is represented by an object of an iterator class.

Iterator TypeRead/Write Iterator can be saved DirectionAccess Random access Read and write Yes Forward and back Rando m Bidirectional Read and write Yes Forward and back Linear Forward Read and write YesForward onlyLinear OutputWrite onlyNoForward onlyLinear InputRead onlyNoForward onlyLinear