Академический Документы
Профессиональный Документы
Культура Документы
Objectives
To know the motivation and benefits of templates To declare template function with type parameters
Template Basics
Templates make it possible to use one function or class to handle many different data types In other words, templates provide the capability to parameterized types in function and classes. With this capability, you can define one function or one class with a generic type that can be substituted for a concrete type by a compiler So, template concept can be used in two different ways:
Template Basics
int maxValue(int value1, int value2) { if (value1 > value2) return value1; else return value2; }
int maxValue(double value1, double { if (value1 > value2) return value1; else return value2; } value2)
int maxValue(char value1, char value2) { if (value1 > value2) return value1; else return value2; }
Generic Function
GenericType maxValue(GenericType value1, GenericType value2) { if (value1 > value2) return value1; else return value2; }
Generic Function
C++ enables you to define a function template with generic types. Match Parameter:
The generic maxValue function can be used to return a maximum of two values of any type, provided that
The two values have the same type The two values can be compared using the > operator
Template Basics
template<class T> T maxValue(T value1, T value2) { if (value1 > value2) return value1; else return value2; } void main() { cout << "Maximum between 1 and 3 is " << maxValue(1, 3) << endl; cout << "Maximum between 1.5 and 0.3 is "<< maxValue(1.5, 0.3) << endl; cout << "Maximum between 'A' and 'N' is " << maxValue('A', 'N') << endl; cout << "Maximum between \"ABC\" and \"ABD\" is "<< maxValue("ABC", "ABD") << endl; }
Generic Function
The template keyword signals the compiler that were about to define a function template.
The keyword class, within the angle brackets, might just as well be called type. The variable following the keyword class (T in this example) is called the template argument.
The function template itself doesnt cause the compiler to generate any code. It cant generate code because it doesnt know yet what data type the function will be working with. It simply remembers the template for possible future use.
Code generation doesnt take place until the function is actually called (invoked) by a statement within the program.
When the compiler sees such a function call, it knows that the type to use, say it is int. So, it generates a specific version of the function for type int, substituting int wherever it sees the name T in the function template. This is called instantiating the function template.
Each instantiated version of the function is called a template function. (That is, a template function is a specific instance of a function template).
The amount of RAM used by the program is the same whether we use the template approach or actually write three separate functions. The template approaches simply saves us from having to type three separate functions into the source file. This makes the listing shorter and easier to understand. If change is required the way the function works, make the change in only one place in the listing instead of three places.
You can use either <typename T> or <class T> to specify a type parameter. Using <typename T> is better because <typename T> is descriptive. <class T> could be confused with class declaration.
Occasionally, a template function may have more than one parameter. In this case, place the parameters together inside the brackets, separated by commas, such as <typename T1, typename T2, typename T3>
Template Issues
When a template function is invoked, all instances of the same template argument must be of the same type. For example, in find(), if the array name is of type int, the value to search for must also be of type int.
int intarray[] = {1, 3, 5, 7}; float f1 = 5.0; int value = find(intarray, f1, 4); //
The compiler expects all instances of atype to be the same type. It can generate a function find(int*, int, int); but it cant generate find(int*, float, int); because the first and second arguments must be the same type.
template<class atype> int find(atype* array, atype value, int size) { // another way of declaration in one line }
};
Shawana Khan
Laila Farrukh
STL Introduction
The STL contains several kinds of entities. The three most important are
Containers Algorithms Iterators
STL Introduction
STL Container
STL Container
Sequence Container
Stores data by position in linear order First element, second element , etc Examples: Array, vector, list, deque
Associate Container Not sequential, instead it uses key to access data Stores elements by key, such as name, social security number or part number Access an element by its key which may bear no relationship to the location of the element in the container Examples: set, multiset, map, multimap Adapter Container Contains another container as its underlying storage structure Examples: stack, queue, priority queue
STL Algorithms
An algorithm is a function that does something to the items in a container (or containers)
Algorithms in STL are standalone template functions The header <algorithm> defines a collection of functions especially designed to be used on ranges of elements A range is any sequence of objects that can be accessed through iterators or pointers, such as an array or an instance of some of the STL containers.
STL Iterator
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 elements to elements, a process, called iterating through the container
Forward Iterator: that can only move forward through the container Bidirectional Iterator: can move backward as well as forward Random Access Iterator: in addition to moving forward and backward, can jump to an arbitrary location
STL Example
Think of vectors as smart arrays. They manage storage allocation for you, expanding and contracting the size of the vector as you insert or erase data. Use vectors much like arrays, accessing elements with the [] operator. Such random access is very fast with vectors. Its also fast to add (or push) a new data item onto the end (the back) of the vector. When this happens, the vectors size is automatically increased to hold the new item.
push_back()
swap()
empty()
back()
pop_back()
size()
Overloaded operator[]
//an array of ints //initialize vector to array //display all elements //insert 115 at element 2