600 likes | 615 Views
Explore list-processing problems with arrays, study sorting and searching techniques, learn about vector<T> class template, and understand the Standard Template Library's role in component-based programming. Illustrate how a class can store a sequence of values effectively.
E N D
Arrays, vector<T>s, and STL Chapter 10
Objectives • Solve list-processing problem using an array • Investigate one-dimensional arrays • Study problems of sorting, searching lists • Study the vector<T> class template • Look at the Standard Template Library (STL) • Indicate STL's role in component-based programming • Illustrate how a class can store a sequence of values C++ An Introduction to Computing, 3rd ed.
Introductory Example:Quality Control • A quality control process requires a program that generates a frequency distribution of how many defective components are found on a collection of robot manufactured circuit boards C++ An Introduction to Computing, 3rd ed.
Behavior For frequency distribution of failures:Enter input file name : failure.txt Now reading file . . .0 failures: 9 99.9%1 failures: 9 99.9% … C++ An Introduction to Computing, 3rd ed.
Objects C++ An Introduction to Computing, 3rd ed.
Operations • Display string on screen • Read string from keyboard • Open stream to file whose name is stored in the string • Read data values from the streamCount occurrences of 0, 1, …, 5 • Display number and % of occurrences of 0, 1, … , 5 C++ An Introduction to Computing, 3rd ed.
Possible Strategies • Six separate variablesint count0, count1 …use switch statement to increment • C-style array provides better solutionint count [6] = {0}; • Creates an indexed variable of 6 elements C++ An Introduction to Computing, 3rd ed.
Algorithm • Prompt for, read file name into inputFileName • Open an ifstream, inStream to file named in inputFileName (error msg if fails) • Initialize numCircuitBoards to 0 • Initialize each integer in count to 0 • Loop • Read integer numFailures from inStream • If eof mark read, exit loop • Increment of count indexed by numFailures • Increment numCircuitBoards • Close inStream • For each index 0 .. 5Display index and count[index] with labels C++ An Introduction to Computing, 3rd ed.
This initializes each element with 0. Coding and Testing • View source code, Figure 10.1 • Note definitionsconst int CAPACITY = 6;int count [CAPACITY] = {0}; • Tells program to set aside memory for 6 integers • The integer sized spaces are called elements • They are indexed from 0 to 5 C++ An Introduction to Computing, 3rd ed.
Four elements, each long integers (which take up 4 bytes each). Arrays • Contrast • Capacity of the arrayThe number of elements it can hold • Size of the arrayThe number of values it actually contains • Note the type of the element is specifiedlong intArray [4] C++ An Introduction to Computing, 3rd ed.
char Arrays and string Variables • Given:const int CAPACITY = 16;charcharArray [CAPACITY];string aString; • The charArray is fixed capacity at 16 • Cannot be changed during run time • The aString variable will automatically adjust its capacity • Depends on what is assigned or read into the variable C++ An Introduction to Computing, 3rd ed.
Declaring Arrays • Note use of the const int CAPACITY on the previous slide • Text recommends use of constants in declaring arrays • Rather than using literals • Source code is more flexible, more easily changed as needed C++ An Introduction to Computing, 3rd ed.
Array Initialization • Givenconst int CAPACITY = 10;int intArray [CAPACITY] = {9,8,7,6,5,4,3,2,1,0}; • Possible to initialize array at declaration time • Must list values within curly brackets { } Note: it is permissible to include less numbers within the curly brackets than the capacity of the array – the remaining values must be assumed to be "garbage" values. C++ An Introduction to Computing, 3rd ed.
Character Arrays • Legacy from C (parent language of C++) • Can be initialized two different wayschar name[10] = {'J','o','h','n',' ','D','o','e'};orchar name[10] = "John Doe"; • The size of the character array or end of the usable sequence is marked by '\0' or the null character C++ An Introduction to Computing, 3rd ed.
The Subscript Operation • Access individual elements within the array • Note use in program of Figure 10.1inStream >> numFailures;if (instream.eof()) break;count [numFailures]++; • The last line increments the slot in the array specified by numFailures There were 58 0s in the data file. count[0] got incremented 58 times C++ An Introduction to Computing, 3rd ed.
Processing Arrays with for Loops • for loop – a counting loop can be used to count through the index values of the arrayfor (int i = 0; i < CAPACITY; i++) // … do something with someArray[i] • Types of tasks to be done with array elements • Sum the elements • Initialize the values • Increment, decrement, multiply by some % C++ An Introduction to Computing, 3rd ed.
Note: the function does not care about the capacity of the array you send it … the second parameter takes care of that Must use an array name, square brackets [ ], and a parameter for size. Use name of the array (without square brackets) to be sent to the function. Arrays as Parameters • Consider a function to sum an arrayint arrayTotal (int numList [], int listSize){ int total = 0; for (int i = 0; i < listSize ; i++) total += numList[i]; return total; } - - - - - cout << "Sum = " << arrayTotal(intList, CAPACITY) ; C++ An Introduction to Computing, 3rd ed.
The typedef Mechanism • Possible to declare a type • In this context it is for declaring array types • Use the type in other declarations const int CAPACITY = 6;typedef int IntegerArray[CAPACITY]; …IntegerArray count = { 0 }; or void initArray (IntegerArray list, int listSize); C++ An Introduction to Computing, 3rd ed.
Out-of-Range Errors • C++ does not check to ensure that indices stay with range specified in array declaration • Note program in Figure 10.2 which demonstrates this • Possible to wander into other memorylocations C++ An Introduction to Computing, 3rd ed.
Predefined Array Operations • String class has many predefined operations • Character array also • <cstring>,<cstdlib>, and <cstdio> • iostream operators >> and << are overloaded • Termination of a cstring by '\n' enables this C++ An Introduction to Computing, 3rd ed.
Predefined Array Operations • Other array types do not have similar operators available • No special characters to terminate the array C++ An Introduction to Computing, 3rd ed.
Problems with C-style Arrays • Capacity of C-style array cannot change during program execution • Object is not self-contained • Does not carry within itself information to describe and operate on it • C-style array needs additional information of its size • An OOP approach provides typesvalarray<T> and vector<T> C++ An Introduction to Computing, 3rd ed.
valarray<T> and vector<T> • These classes are containers which C-style problems • Their capacities can change • They have several built in operators • valarray<int> intList; • Specifies an array object which contains integers • vector <string> nameList • Specifies an array object which contains strings C++ An Introduction to Computing, 3rd ed.
Selection Sort • Make a number of passes through the list or part of the list • On each pass, select one item to be correctly positioned • Find smallest element • Swap with first element • Repeat with the rest of the list – successively smaller sublists C++ An Introduction to Computing, 3rd ed.
Linear Insertion Sort • Repeatedly insert a new element into a list of already sorted elements • Resulting list is still sorted C++ An Introduction to Computing, 3rd ed.
Quicksort • Very fast, often implemented by recursion • Strategy • Choose some element called a pivot • Perform exchanges so that • All elements less than the pivot are to the left • All elements greater are to the right • Divide the two sublists each with their own pivots, perform same type of exchanges C++ An Introduction to Computing, 3rd ed.
Quicksort • Let 75 be the pivot • Look from right for a number < 75 • Look from left for number > 75 • Swap the numbers C++ An Introduction to Computing, 3rd ed.
Quicksort • Continue on, from right and from left, making exchanges as needed • Then swap the pivot with this middle number C++ An Introduction to Computing, 3rd ed.
Quicksort • Now perform the quicksort algorithm on the two remaining sublists • This can be done recursively • The anchor is when the list examined is empty or contains a single element • Inductive step is when list has > 2 elements C++ An Introduction to Computing, 3rd ed.
Linear Search • Searches consecutive elements in the list • Begin with first • Continue until item found or end of list reached C++ An Introduction to Computing, 3rd ed.
Repeat searching sublists as needed. Note that searchVal may not be found Binary Search • More efficient algorithm for searching a sorted list (for n items, max log2n comparisons) • Start at middle element • Compare searchVal with that element • If middle < , go to middle of right sublist • If middle > , go to middle of left sublist 25 C++ An Introduction to Computing, 3rd ed.
Example ProblemProcessing Employee Information • Keep track of employee seniority, salaries • Data on a file, employeeData.txt • Employee name and salary in the file from highest salary to lowest • We need a program to read this file, create another with employees in alphabetical order C++ An Introduction to Computing, 3rd ed.
Objects C++ An Introduction to Computing, 3rd ed.
Operations • Open a stream to an input file • Read a sequence of employee records from a file stream • Close a file stream • Sort a sequence of employee records • Open a stream to an output file • Write a sequence of employee records to a file stream C++ An Introduction to Computing, 3rd ed.
Algorithm • Open ifstream named inStream to "employeeData.txt" • Loop • Read a line from inStream into empLine • If the eof mark read, terminate repetition • Append empLine to empVector Endloop • Close inStream • Sort lines in empVector • Open ofstream named outStream to "payrollData.txt"(if fails, display error message, terminate algorithm) • For each index i of empVector Write empVector[i] to outStream • Close outStream C++ An Introduction to Computing, 3rd ed.
Coding and Testing • View source code, Figure 10.3 • Sample run, listing of output file below Fig 10.3 C++ An Introduction to Computing, 3rd ed.
The vector<T> Class Templates • Function templates • Patterns for functions • Compiler creates actual function definitions • Type parameter is place holder for a type template <typename Item>inline void swap( Item& first, Item& second){ Item temp = first; first = second; second = temp;} What are some sample calls to this function template? C++ An Introduction to Computing, 3rd ed.
The vector<T> Class Templates • Type independent patterns from which actual classes are defined • Useful for generic container classes • One of simplest containers is the vector<T> class • When you declare vector<int> intVec; • Compiler creates definition of vector with int replacing all the references to T • It would create a different definition if another is declared with a different type C++ An Introduction to Computing, 3rd ed.
5 8 13 21 08 14 19 size capacity data 0 1 2 3 4 5 6 7 Vector Attributes A vector has several attributes, including its • Data -- the values it contains. • Size -- the number of values it contains; and • Capacity -- the number of values it can store before having to grow. C++ An Introduction to Computing, 3rd ed.
5 8 13 21 08 14 19 size capacity data 0 1 2 3 4 5 6 7 size() and capacity() • From this, it should be obvious that the vector function member size() simply returns the value of its size attribute: • A vector also has a function member named capacity() that returns the value of its capacity attribute. C++ An Introduction to Computing, 3rd ed.
0 0 f size capacity data 8 8 8 8 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 size size capacity capacity data data 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 Declarations: 3 Forms vector<double>aVector; // empty const int N = 8; // N default vector<double> aVector(N); // values const int N = 8; // N specified vector<double> aVector(N, 1); // values C++ An Introduction to Computing, 3rd ed.
8 8 8 8 Hi 0 0 Hi 0 Hi Hi 0 0 Hi 0 Hi Hi 0 0 Hi size size capacity capacity data data 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 Vector Declarations • You can pass any type to a vector when it is declared: const int N = 8; vector<bool> boolVec(N, false); const int N = 8; vector<string> stringVec(N, “Hi”); C++ An Introduction to Computing, 3rd ed.
0 0 f size capacity data 1 8 13 size capacity data 0 1 2 3 4 5 6 7 Vector push_back() • Values can be appended to a vector using the push_back() function member • Causes the vector to “grow” if necessary. vector<double> aVector; // empty aVec.push_back(13); C++ An Introduction to Computing, 3rd ed.
3 8 13 6 21 size capacity data 0 1 2 3 4 5 6 7 Appending (Ct’d) • Subsequent calls to push_back() continue to append: aVec.push_back(6); aVec.push_back(21); • When the size equals the capacity, a call to push_back() causes the vector to grow again. • The only limit on a vector’s growth is the amount of memory available. • See Figure 10.4 for use of push_back() C++ An Introduction to Computing, 3rd ed.
2 3 8 8 13 13 6 6 21 size size capacity capacity data data 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 Vector pop_back() • To remove the most recently appended value, the vector function memberpop_back() can be used: aVec.pop_back(); • Note that both push_back() and pop_back() alter size. C++ An Introduction to Computing, 3rd ed.
2 8 13 6 size capacity data 0 1 2 3 4 5 6 7 Vector front() and back() • The first and last values in a vector can be retrieved with the front() and back() function members: double alpha = aVec.front(); // alpha == 13 double omega = aVec.back(); // omega == 6 • The front() and back() function members provide a convenient way to access the ends of a vector without finding using subscripts. C++ An Introduction to Computing, 3rd ed.
2 8 13 6 size capacity data 0 1 2 3 4 5 6 7 Vector Subscript • Like a string, the individual values in a vector can be accessed using the subscript ([]) operator. See Figure 10.5 for proper use of the subscript operator double first = aVec[0]; // first == 13 double second = aVec[1]; // second == 6 • The subscript operation aVec[i] provides a convenient way to access the value in aVec whose index is i, where i is a for loop control variable. C++ An Introduction to Computing, 3rd ed.
2 8 13 6 size capacity data 0 1 2 3 4 5 6 7 Safe Vector Element Access • The subscript operator does not check that the index being accessed is valid. • The at() function member does check the index for validity, making it safer, but slower. double first = aVec.at(0); // first == 13 double second = aVec.at(1); // second == 6 C++ An Introduction to Computing, 3rd ed.
vector<t> Objects vs. C-style Arrays • Advantages of vector<t> • Capacity can change during execution • A self contained object • A class template, can be used for variety of types • Advantages of arrays • Less overhead (time, code size) • Can be more careful in memory use • Dynamic allocated arrays in C, sometimes sufficient without vector overhead C++ An Introduction to Computing, 3rd ed.
Array and vector<t> Limitations • Frequent insertions and deletions are time consuming • To insert the 56, Many elements must be shifted C++ An Introduction to Computing, 3rd ed.