CS 162 Lecture Notes - Lecture 20: Standard Template Library

22 views5 pages
CS 162 Lecture 20 Templates
Function Templates
o We hae a geeral algorith hich does’t chage ee if types chage
o Algorithm Abstraction: expressing algorithms in a very general way so that we
can ignore incidental detail and concentrate on the substantive part of the
algorithm
o Example:
Swap
o Make a template function which can take any type
Template <class T>
Void swap(T& v1, T& v2){
T temp;
Temp = v1;
V1 = v2;
V2 = temp;
}
Details
o Template <class T>
Referred to as the template prefix
Tells the compiler that the definition that follows is a template
T is a type parameter
o Template definition is a large collection of function definitions
o Compiler does not actually produce definitions for every single type
o One will be produced for every type which uses the template in the program
o Compilers are not consistent in their treatment of templates
Needs to be defined in the same file it is invoked
.hpp
Templated Classes
o Work the same way as templated functions
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in
o All functions within the class will operate on the provided types
o Scope with ClassName<T>::functionname()
o Each function needs the Template prefix
Vector: and Example of a Templated Class
o Arrays that can grow and shrink in length while the program is running
o Formed from template class in the Standard Template Library
o Has a base type and stores a collections of this base type
Vector <int> v;
o Still starts indexing at zero, can still use hard brackets to access things
o Use push_back to add one element to the end
o Number of elements ==size
o How much memory currently allocated == capacity
When capacity is greater than or equal to size
Typically doubles when size is greater than capacity
Demo (code taken from instructor)
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents