Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Unit VI

2  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.

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

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

5

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

7  #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, 151.22) = " << max(111.41, 151.22) << endl ;  return 0;  }

8  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  };

9  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.

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

11  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.

12  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.

13

14  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

15  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

16 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

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

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

19  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.

20  Same as set, except that duplicates are allowed

21  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)

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

23 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

24  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

25  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.

26 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

27

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

29 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

30

31

32


Download ppt "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."

Similar presentations


Ads by Google