Lecture 12OutlineTemplates 1Templates 2Templates 3Vectors 1Vectors 2Constructors 1Constructors 2AccessorsMutators and OperatorsExamples 1Examples 2Examples 3Filling a Vector 1Filling a Vector 2In-class Exercise 1In-class Exercise 2Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1Lecture 12Log into Linux. Copy files on csserver in /home/hwang/cs215/lecture12/*.*Reminder: Practical Exam 1 is Wednesday 3pm-5pm in KC-267.Questions about Project 2 or Homework 6? Submission system is set up to accept submissions for both.Note: Please put your name (in a comment) in every file you submit!Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 2OutlineNote: this material is not directly in the textbookIntroduction to templates and the STLSTL vectorsMonday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 3TemplatesOften we want to use a container class to hold elements of different types in the same program. For example, a bag of integers to hold ages and a bag of strings to hold names.To use the implementation technique from last week, we would need to write two separate implementations with different class names E.g., integer_bag and string_bag. (Or use two different namespaces and always use qualified names. E.g. int_bag::bag and str_bag::bag.)Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 4TemplatesThe only difference between the two classes would be the typedef for value_type. Nothing else changes. However, it is tedious and error prone to have duplicate code.What is needed is a type parameter. This idea is like a regular data parameter except that it allows different types to be used.The built-in array is like this already. When we want an array, we just say what the element type is.Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 5TemplatesThe C++ mechanism for defining type parameters is called a template. Later in this course, we will write our own template functions and classes.Today we just want to start looking at the C++ Standard Template Library (STL). The STL defines 10 container classes that are categorized according to the ordering of the elements and the different kinds of operations that access the data.Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 6VectorsThe basic STL sequence container is the vector. A vector is like an array with added features. These are the most useful ones:it has constructors that initialize the vector, so that a vector is always in a valid stateelements can be added dynamically to the end of a vectorthere is a member function that will return the number of elements in a vector.More details on vectors can be found on-line.Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 7VectorsThe vector<T> type is a template. It is defined in the <vector> library and is in namespace std.To use a template type, the actual type parameters are given in <>'s after the type name when declaring variables. Here are some examples using vector, which has one type parameter:vector<int> intVector; // empty vectorsvector<double> realVector;vector<string> strVector;vector<Rational> ratVector;Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 8ConstructorsThe vector default constructor creates an empty vector (i.e., 0 elements). Here are some other constructors:// 5 elements of T() = 0vector<int> intVector2(5); // 31 elements of T() = 0/1vector<Rational> ratVector2(31); // 7 elements of 100vector<int> intVector3(7, 100); // 7 elements of 4/3// used Rational constructor directlyvector<Rational> ratVector3(7, Rational(4,3));Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 9ConstructorsThere is no built-in initialization syntax like there is for arrays, but we can use an array to initialize a vector:int intArray[] = {9, 2, 7, 3, 12};vector<int> intVector4(intArray, // addr of 1st element intArray + sizeof(intArray)/sizeof (int)); // addr of the element one past the end of the arrayThe built-in sizeof function returns the number of bytes in a variable or a type, so sizeof(intArray)/sizeof(int) computes the number of elements in intArray.Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 10AccessorsAccessor operations of vector include:size – returns the number of elementsempty – returns true if vector has no elements; false otherwise[ ] - indexing, like arrays, no bounds checkingat – also indexing, but checks boundsback – returns a reference to the last element that can be used to access the valueMonday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 11Mutators and OperatorsMutator operations of vector include:push_back – add an element to the endpop_back – remove an element from the endresize – change the size of the vector; truncate if made smaller, fill if made largerclear – make the vector emptyback – returns a reference to the last element that can be used to change it.Assignment (operator=) is defined for vectors. It causes the left operand to become a copy of the right operand.Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 12ExamplesExamine file vector-examples.cpp. Since vectors are class objects, when they are passed as received-only parameters, they are passed using a const reference parameter.Note that the type returned by size( ) is size_t. As usual, g++ will give a warning if it is compared to an int.void PrintVector (const vector<int> & v){ for (size_t i = 0; i < v.size(); i++) cout << "Element " << i << ": " << v[i] << endl;} // end PrintVectorMonday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 13Examples// Demonstrate empty() and size()if (intVector.empty()) cout << "intVector is empty\n";else cout << "intVector has " << intVector.size() << "elements\n";// Demonstrate use of back() on either side of =cout << "The last element of intVector2 is " << intVector2.back() << endl;intVector2.back() = 5;cout << "The last element of intVector2 is now " << intVector2.back() << endl;// Demonstrate use of size() and []cout << "The elements of intVector4 are:\n";PrintVector (intVector4);Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 14Examples// Double size of intVector4, fill with T()=0intVector4.resize(2*intVector4.size());// Resize
View Full Document