Mr. Dave Clausen La Cañada High School

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 10.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
Chapter 8 Arrays and Strings
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Vectors Mr. Dave Clausen La Cañada High School.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 9 Structured Data: Structs and ADTs (Data Base Programs with C++) Mr. Dave Clausen La Cañada High School.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays Chapter 7.
Chapter VII: Arrays.
Arrays.
User-Written Functions
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
The Sequential Search (Linear Search)
Array An “average.cpp” program
Chapter 7 Part 1 Edited by JJ Shepherd
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
New Structure Recall “average.cpp” program
Chapter 7: Arrays.
C Arrays.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
One-Dimensional Array Introduction Lesson xx
7 Arrays.
Chapter 8 Slides from GaddisText
Arrays Kingdom of Saudi Arabia
Pointers and Pointer-Based Strings
Chapter 8 Arrays Objectives
Chapter 6: Repetition Statements
Standard Version of Starting Out with C++, 4th Edition
Review of Everything Arrays
Building Java Programs
7 Arrays.
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 8 Arrays Objectives
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Arrays A few types Structures of related data items
Dr. Sampath Jayarathna Cal Poly Pomona
The Sequential Search (Linear Search)
The Sequential Search (Linear Search)
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Mr. Dave Clausen La Cañada High School Chapter 8: Vectors Mr. Dave Clausen La Cañada High School Mr. Dave Clausen

Objectives Understand the role of a vector as a fundamental data structure Declare and use a vector variable Write functions that process vectors Sort and search a vector Dave Clausen

Variable Types So far we have been using 4 simple data types: double, int, char, bool We are starting to create our own user defined types called “Structured Types” Our first Structured type was the enumerated type. Our second Structured type is called an “array” (in this case a vector, or safe array). Dave Clausen

Vectors Arrays or vectors allow us to replace long lists of variables (that have different names) with one variable name (storing the same type of data). For example, we can store several grades and perform calculations on them, without losing the actual grades. Vectors are data structures where each element is accessed using indexed positions. Each index describes the relative position of an element in the vector. Dave Clausen

Vectors Store several objects of the same type in sequential order 1 2 3 4 5 0 1 2 3 4 5 6 7 Store several objects of the same type in sequential order Locate objects with an integer index A data structure - can treat many things as one thing Dave Clausen

Declaring a Vector Variable #include "apvector.h” //.h for Borland 5.02 int main() { apvector<int> numbers; vector type item type vector variable name Item type can be any data type. A vector has no cells for items by default; its length is 0 Dave Clausen

Declaring Vectors When declaring a vector, we need to tell the computer: the type of items to be stored (int, double, char, or apstring), called the base type these data elements must all be the same data type We don’t have to declare the maximum number of items to be stored. A vector can be “resized” while the program is running. Dave Clausen

Format for Declaring Vectors The general format is: apvector <component type> <variable name> (<integer value>); We must: #include “apvector.h” Borland 5.02 start with: apvector component type is any predefined, or user defined data type: this must be in angle brackets < > variable name is any valid identifier The integer value declares how many memory locations to reserve counting from 0 to N-1 in parentheses. apvector uses dynamic memory, so you can ask the user how much memory to reserve. Dave Clausen

Specifying a Vector’s Length #include "apvector.h” //.h for Borland 5.02 int main() { apvector<int> numbers(5); vector length vector type item type vector variable name numbers 0 1 2 3 4 A vector’s length can be specified when the variable is declared. Items in cells are undefined. Dave Clausen

Examples of vector declarations apvector <int> hours; //Size is zero apvector <int> integers (100, 0); //Size = 100 //Every value = 0 cout<<“Enter the number of stocks to track: ”; cin>>num_stocks; apvector <double> stock_prices (num_stocks ); #include “apvector.h” //For Borland 5.02 #include “apstring.cpp” const int MAX_LIST_SIZE = 20; apvector <apstring> words (MAX_LIST_SIZE ); Dave Clausen

Vector Indices and limits Individual items, elements, or components in the vector are referred to using an “index” or “subscript”. This index must be in the range of zero to N-1 Range Bound Error If you use an index value less than zero or greater than N-1 The C++ compiler will not stop the program, nor will there be an error message. An assertion in apvector will halt the program with an error message. Dave Clausen

Vectors and indices ? ? ? ? ? If we define the vector: apvector <int> list (5) //for an apvector we could visualize it as follows: note that we start counting the indices from 0 (zero) to N-1 (one less element than declared) ? ? ? ? ? Dave Clausen

Range Bound Errors numbers 1 2 3 4 0 1 2 3 4 5 int main () { apvector<int> numbers(5); for (int i = 0; i <= numbers.length(); ++i) numbers[i] = i; numbers 1 2 3 4 0 1 2 3 4 5 The program will halt with a run-time error when numbers[5]is referenced Dave Clausen

Vector Elements The contents of each “box” is called an “element” or “component” of the vector, and may store one int, double, char, bool, or apstring value (whatever was defined as the base type or component type). When the Vector is declared, each element in the vector is in an “unpredictable state” until you assign values to each element. Dave Clausen

Initializing A Vector Since each element in a vector is undefined, it is considered good programming to “initialize” each element of each vector that you declare. This means assigning a value to each element that you would not expect to see as a typical value in that vector. Dave Clausen

Initializing Values For example: A grade of -99 is rarely seen in the normal context of grades, so assigning every element equal to -99 (or another negative number) is a good choice. If you were storing characters in a vector, you may want to initialize each element to contain one space. ‘ ‘, or the null character ‘\0’, which contains nothing. Dave Clausen

Specifying a Fill Value vector fill value #include "apvector.h" int main() { apvector<int> numbers(5, 1); vector length vector type item type vector variable name numbers 1 1 1 1 1 0 1 2 3 4 A default value for each item can be specified when a vector is declared. Dave Clausen

Initializing A Vector Vectors are easily initialized when they are declared using the “fill value”. cout<<“Enter the number of elements for the vector: “; cin>>vector_size; cout<<“Enter the initializing value for the vector: “; cin>>initial_value; apvector <int> list (vector_size, initial_value); Dave Clausen

A safe array class (Vectors) The safe array class should include the following features: It should support the subscript or index operation. The user can specify the size of the “vector”. The “array” should be easily initialized with values set to a “fill value”. Vectors should support the assignment statement to copy the contents of one vector into another. Vectors should be able to adjust their size during assignment operations. Dave Clausen

Comparing an Array with a Vector Here is a sample program using arrays: arrayav.cpp arrayav.txt Here is a sample program using apvector: vectorav.cpp vectorav.txt The biggest difference between the two programs is that “vectorav.cpp” allows the user to declare how many elements they want to use in the vector. Two other points are important to notice: #include “apvector.h” (include the header file apvector.h, use quotes “ “) It is not necessary to build a project when using template classes. (Unless it also uses apstring, a non templated class) Dave Clausen

apvector is a Template Class A template class is a class that allows the user to specify what the data type of the instances (variables, objects) are. It’s component types are specified as parameters. In the apvector class we can declare: apvector <int> int_vector; apvector <double> double_vector(size); apvector <apstring> string_vector(size, init_value); The angle brackets < > surround the data type. Watch for the following notations in the class: template <class itemType> //itemType behaves like a apvector <itemType> //formal parameter in the class Dave Clausen

The length function The apvector class has a member function to indicate the “size” of the vector. This indicates the length that the vector was declared, not the number of valid elements that are stored in the vector. vector_size = list .length( ); //Since length is a member function of the apvector class, we use the dot notation. Dave Clausen

The Resize Function apvector includes a function to “resize” the vector // description: resizes the vector to newSize elements // precondition: the current capacity of vector is length( ); //newSize >= 0 // postcondition: the current capacity of vector is newSize; for //each k // such that 0 <= k <= min(length, newSize), vector[k] // is a copy of the original; other elements of vector are // initialized using the 0-argument itemType constructor // Note: if newSize < length, elements may be lost Dave Clausen

Example of Resize const int SIZE = 5; apvector <int> scores(SIZE); cout<<scores.length( ); //Ask the user for the new size of the vector cout<<“Enter the number of elements for the vector: “; cin>>new_size; //Resize the vector, if it is not too small if (new_size > scores.length( ) ) scores.resize(new_size); //Remember: if the new_size was smaller than the original vector length, data can be lost. Dave Clausen

Structured Types A vector is a structured type. Vectors can vary in size, therefore, few commands can be used on the entire vector. You cannot use “cin” or “cout” with the entire vector, only with individual elements in the vector. Dave Clausen

Operations on Data In A Vector A definite or indefinite loop is used to perform many operations with a vector, including: Entering the data Printing the data Searching the vector for a key value Sorting the data in the vector Performing calculations on the values in the vector. Dave Clausen

Entering Data into a Vector for(int index=0; index < grade.length( ); ++index) { cout<<“Enter Grade # “<< index <<“ : “; cin>>grade [ index ]; } An indefinite loop would be much better if you don’t want to fill all the elements of the vector. 95 87 73 99 85 Dave Clausen

Displaying the contents of a Vector void Print_Vector (const apvector<double> &grade) { for(int index=0; index < grade.length( ); ++index) cout<<“grade # “<<index<<“ is: “ <<grade[index] <<endl;. } //Use constant reference parameters when vectors are // used but not changed in a function. Dave Clausen

Displaying the contents of a Vector using rows & columns for(int index=0; index < grade.length( ); ++index) { cout<<setw(5) <<grade[index] ; if (index % 10 = = 0) cout<<endl; } //Students: Modify this to fix the logic error here. This displays 10 grades across a row before sending a carriage return (endl) for the next row. Dave Clausen

Vector Algorithms: Average of a Vector To find the average of all the elements in a vector: sum = 0; for(int index=0; index < numscores; ++index) sum =sum + scores [index]; assert(numscores !=0); average = double(sum) / double (numscores); //don’t forget explicit type conversion //numscores is the logical size of the vector. Dave Clausen

Vector Algorithms: Maximum score of a Vector To find the maximum score of all the elements in an vector: max = scores[0]; for(int index=0; index < scores.length( ); ++index) if (scores[index] > max) max = scores[index]; Dave Clausen

Vector Algorithms: Finding the Index of the Maximum score of a Vector To find the index (position) of the maximum score of all the elements in a vector: index_max = 0; for(int index=0; index < scores.length( ); ++index) if (scores[index] > scores[index_max]) index_max = index; Dave Clausen

Vector Parameters and Functions //Function: Get_Data //Get scores from the user at the keyboard until //the SENTINEL is entered. // //Inputs: list //Outputs: a vector of integers representing the list and logical_size //representing the vectors logical size void Get_Data (apvector <int> &list , int & logical_size); Dave Clausen

Vectors and Functions Vectors need to be passed as reference parameters to functions. Be aware that any changes to the vector in a function, change the actual vector, not a copy of the vector as is done with value parameters. The vector is not actually passed to the function, only the address of the vector, as is the case with reference parameters. You should pass the actual number of valid elements in the vector to a function, but you do not need to send its size. We can find the physical size of the vector using the length function. Dave Clausen

Vectors and Functions 2 list.length( ); represents the physical size of the vector. The logical_size parameter in Get_Data function represents the logical size of the vector when the function returns the value. The physical size of an vector is the number of memory units declared for storing data items in the vector. The logical size of an vector represents the actual number of data items in the vector at any given time. Use const apvector <basetype> &vector_name when you want to ensure that no changes occur in the vector. (i.e. Display_Output function) Dave Clausen

Physical Size vs Logical Size When created, vectors have a fixed capacity (number of physical cells) The number of data items (logical size of the list) may not equal the capacity vector 0 1 2 3 4 Occupied cells = logical size Dave Clausen

Physical Size vs Logical Size 2 int main() { apvector<int> numbers(5); for (int i = 0; i < 4; i++) numbers[i] = i; numbers 1 2 3 0 1 2 3 4 Physical size = number of cells declared in vector Logical size = number of items currently stored and used by the program Dave Clausen

Entering Data into a Vector Using Indefinite Loops A primed while loop will allow the user to enter data until they wish to quit by entering an input SENTINEL. This method also lets you calculate the logical length of the vector. P434vect.cpp P434vect.txt Dave Clausen

Example: Interactive Input int main() { apvector<int> v(10); // Start with length of 10 int data; int count = 0;   cout << "Enter a number or -999 to quit: "; cin >> data; while (data != -999) if (v.length() = = count) // Expand by factor of 2 if no room v.resize(count * 2); v[count] = data; ++count; } if (v.length() != count) // Shrink to number of items stored v.resize(count); Try to keep the physical size and the logical size the same. Dave Clausen

Sorting & Searching Vectors Sequential Search Selection Sort Bubble Sort. Insertion Sort Dave Clausen