Lecture 12 Log 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 1
Outline Note: this material is not directly in the textbook Introduction to templates and the STL STL vectors Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 2
Templates Often 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 3
Templates The 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 4
Templates The 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 5
Vectors The 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 state elements can be added dynamically to the end of a vector there 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 6
Vectors The 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; vector<double> realvector; vector<string> strvector; vector<rational> ratvector; // empty vectors Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 7
Constructors The vector default constructor creates an empty vector (i.e., 0 elements). Here are some other constructors: // 5 elements of T() = 0 vector<int> intvector2(5); // 31 elements of T() = 0/1 vector<rational> ratvector2(31); // 7 elements of 100 vector<int> intvector3(7, 100); // 7 elements of 4/3 // used Rational constructor directly vector<rational> ratvector3(7, Rational(4,3)); Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 8
Constructors There 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 array The 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 9
Accessors Accessor operations of vector include: size returns the number of elements empty returns true if vector has no elements; false otherwise [ ] - indexing, like arrays, no bounds checking at also indexing, but checks bounds back returns a reference to the last element that can be used to access the value Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 10
Mutators and Operators Mutator operations of vector include: push_back add an element to the end pop_back remove an element from the end resize change the size of the vector; truncate if made smaller, fill if made larger clear make the vector empty back 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 11
Examples Examine 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 PrintVector Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 12
Examples // 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 13
Examples // Double size of intvector4, fill with T()=0 intvector4.resize(2*intvector4.size()); // Resize intvector4 to 3 elements, truncate intvector4.resize(3); // Add some elements to end of intvector4 intvector4.push_back(5); intvector4.push_back(1); // Remove elements from end of intvector4 until empty while (!intvector4.empty()) { cout << "Removing end element " << intvector4.back() << endl; intvector4.pop_back(); } Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 14
Filling a Vector Unlike an array, the "slots" of a vector do not exist unless they are created during construction or by using push_back. But this means we can write a function that starts with an empty vector and fills it from values read in from an input stream (cin, an ifstream, or even an istringstream). E.g., ifstream instream ("inclass12.dat"); ReadVector(intVector, instream); Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 15
Filling a Vector // Fills a vector from an input stream void ReadVector (vector<int> & v, istream & in) { int value; v.clear(); // Want only elements from stream // Without clear() would be AppendToVector // read integers until end of file while (in >> value) v.push_back(value); // add to end of v } // end ReadVector Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 16
In-class Exercise Add a function SearchVector to the example program. This function receives a vector of integers and a target integer to search for. It returns the index (type size_t) of the target if found or the size of the vector if not found. Add code to the end of the main program to ask the user for a target value, call SearchVector, and display the index if the target was found or a message that the target was not found. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 17
In-class Exercise Add a function JoinVectors to the example program. This function receives two vectors of integers and returns a (new) vector of integers that contains the elements of the first vector followed by the elements of the second vector. Add code to the end of the main program to join intvector and intvector3, and display the resulting vector. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 18