Lecture 4
Learning objectives
After this class (which mostly reviews C++ material that you should already know!), you should be able to:
- Explain why templates are normally defined in .h files.
- Define and use template functions and classes.
- Explain how a friend function is different from others.
- Use basic features of the STL
vector
andlist
classes.
Reading assignment
- Chapter 1, sections 1.6-1.7 (except section 1.6.4).
- www.sgi.com/tech/stl has a good reference on STL.
- Lecture: Templates.
Exercises and review questions
- Exercises and review questions on current lecture's material
- Why are templates normally defined in .h files?
- Comment out the header file guards in
largest.h
, includelargest.h
twice inuselargest.cpp
, and try compiling. Why does it not compile?- Write a template function called
average
, which computes the average of an array, and give an example code demonstrating its use.- Write a template class called
complex
, which stores a complex number. The components may either be int, float, or double. Include an operator for adding two complex numbers, and for outputting a complex number. (Note: A complex number is a pair of numbers (x,y). The sum of complex numbers c1 = (x1, y1) and c2 = (x2, y2) is defined as the complex number (x1+x2, y1+y2).)- Why was the operator
<<
made a friend in thePair
class?- Write a program that will define a variable of STL's
list
type, so that it can storeint
s. Then insert a few integers into it, and use an iterator to go through the entire list and output its contents.- Questions on next lecture's material
- None.
Last modified: 7 Sep 2011