An Introduction To Software Development Using C++ Class #18: Vectors & Arrays
Problems With Your Homework #2 “No hardcoding of a solution is permitted. Your program should be able to be run for any amount of time (e.g. two days) and produce the correct output for the entire time.”
Thoughts On Homework #3: A Lot Of Subroutine Calls Return Addresses North South West East Main0 1 2 3 4 5 6 7 8 9 10 11 North South West East North South West East North South West Solution? Exit
Thoughts On Homework #3: When To End? North South West East class Stoplight { private: startTime = time(0); } If (time(0) – startTime >= 60) exit;
Thoughts On Homework #3: How To Handle The Emergency Vehicle North South West East 1. East is processing when the emergency vehicle arrives. 2. East passes control to West. 3. West commands everyone else to go to red and it goes to green. 4. West processes the emergency vehicle and then resumes normal operation.
A Common Problem • A common problem in programming is not knowing how many of something you have while you’re writing a program – happens a lot. • The Standard C++ Library has a ready-made solution: the standard container classes. The container classes are one of the real powerhouses of Standard C++. Image Credit: drvidyahattangadi.com
Say Hello To Vectors • A vector is a collection of objects, all of which have the same type. • Every object in the collection has an associated index, which gives access to that object. • A vector is often referred to as a container because it “contains” other objects. Image Credit: play.google.com
How Do We Use Vectors? • To use a vector, we must include the appropriate header. #include <vector> Image Credit: sivers.org
Introducing Vectors • The vector class is a template, which means that it can be efficiently applied to different types. • That is, we can create a vector of shapes, a vector of dogs, a vector of strings, etc. • Basically, with a template you can create a “class of anything.” • To tell the compiler what it is that the class will work with (in this case, what the vector will hold), you put the name of the desired type in “angle brackets,” which means ‘<’ and ‘>’. • So a vector of string would be denoted vector<string>. When you do this, you end up with a customized vector that will hold only string objects, and you’ll get an error message from the compiler if you try to put anything else into it. Image Credit: http://www.viralnova.com/crazy-xray-photos/3/
All About Templates • A vector is a class template. • C++ has both class and function templates. • Templates are not themselves functions or classes. • Instead, they can be thought of as instructions to the compiler for generating classes or functions. • The process that the compiler uses to create classes or functions from templates is called instantiation. • When we use a template, we specify what kind of class or function we want the compiler to instantiate. Image Credit: www.digital-builder.co.uk
How To Initialize A Vector vector<int> v1(10); // v1 has ten elements with value 0 vector<int> v2{10}; // v2 has one element with value 10 vector<int> v3(10, 1); // v3 has ten elements with value 1 vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1 Image Credit: support.radioshack.com
How To Initialize A Vector • We can usually omit the value and supply only a size. • In this case the library creates a value-initialized element initializer for us. This library-generated value is used to initialize each element in the container. • The value of the element initializer depends on the type of the elements stored in the vector. • If the vector holds elements of a built-in type, such as int, then the element initializer has a value of 0. If the elements are of a class type, such as string, then the element initializer is itself default initialized: vector<int> ivec(10); // ten elements, each initialized to 0 vector<string> svec(10); // ten elements, each an empty string Image Credit: www.youtube.com
Adding Things To A Vector • Since vector expresses the concept of a “container,” there must be a way to put things into the container and get things back out of the container. • To add a brand-new element on the end of a vector, you use the member function push_back( ). • The. reason the name of this member function might seem a bit verbose – push_back( ) instead of something simpler like “put” – is because there are other containers and other member functions for putting new elements into containers. • For example, there is an insert( ) member function to put something in the middle of a container. • There’s also a push_front( ) (not part of vector) to put things at the beginning. Image Credit: blogs.courier-journal.com
How Do You Get Things Out Of A Vector? • So you can put new elements into a vector with push_back( ), but how do you get these elements back out again? We make the vector look like an array. • The array is a data type that is available in virtually every programming language so you should already be somewhat familiar with it. • Arrays are aggregates, which mean they consist of a number of elements clumped together. The distinguishing characteristic of an array is that these elements are the same size and are arranged to be one right after the other. • Most importantly, these elements can be selected by “indexing,” which means you can say “I want element number n” and that element will be produced, usually quickly. • Although there are exceptions in programming languages, the indexing is normally achieved using square brackets, so if you have an array a and you want to produce element five, you say a[4] (note that indexing always starts at zero). • This very compact and powerful indexing notation is incorporated into the vector. Image Credit: www.dynafile.com
Sample Program: Print Out File With Line Numbers// File Fillvector.cpp // Copy an entire file into a vector of string #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; int main() vector<string> v; ifstream in("18 Class 01 Fillvector.cpp"); string line; while(getline(in, line)) v.push_back(line); // Add the line to the end // Add line numbers: for(int i = 0; i < v.size(); i++) cout << i << ": " << v[i] << endl; } 0: // File Fillvector.cpp 1: // Copy an entire file into a vector of string 2: 3: #include <string> 4: #include <iostream> 5: #include <fstream> 6: #include <vector> 7: 8: #include <unistd.h> 9: #include <string.h> 10: 11: using namespace std; 12: 13: int main(){ 14: 15: vector<string> v; 16: 17: ifstream in("18 Class 01 Fillvector.cpp"); 18: string line; 19: 20: while(getline(in, line)) 21: v.push_back(line); // Add the line to the end 22: 23: // Add line numbers: 24: for(int i = 0; i < v.size(); i++) 25: cout << i << ": " << v[i] << endl; 26: 27: } stringobjects are pushed onto the back of the vector v Once the while loop completes, the entire file is resident in memory, inside v 1
Sample Program: Place Integers Into A Vector // File:Intvector.cpp // Creating a vector that holds integers #include <iostream> #include <vector> using namespace std; int main() { vector<int> v; for(int i = 0; i < 10; i++) v.push_back(i); for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; for(int i = 0; i < v.size(); i++) v[i] = v[i] * 10; // Assignment for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; } // end of main 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, You also have the ability to assign (and thus to change) to any element of a vector, also through the use of the square-brackets indexing operator. 2
Vector In-Class Programming Assignment • Create a vector<float> and put 25 floating-point numbers into it using a for loop. – Display the vector. • Create three vector<float> objects and fill the first two as in the previous exercise. – Write a for loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vector. – Display all three vectors. • Create a vector<float> and put 25 numbers into it as in the previous exercises. – Now square each number and put the result back into the same location in the vector. – Display the vector before and after the multiplication. Image Credit: blog.intellisource.com
Arrays • An array is a consecutive group of memory locations that all have the same type. • To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array. • This figure shows an integer array called c that contains 12 elements. You refer to any one of these elements by giving the array name followed by the particular element’s position number in square brackets ([]). • The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array). • The first element has subscript 0 (zero) [zero indexing] • Thus, the elements of array c are c[0] (pronounced “c sub zero”), c[1], c[2] and so on. • The highest subscript in array c is 11, which is 1 less than the number of elements in the array (12). Array names follow the same conventions as other variable names.
Arrays • A subscript must be an integer or integer expression (using any integral type). • If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. • Example, if we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement: adds 2 to array element c[11]. • A subscripted array name is an lvalue—it can be used on the left side of an assignment, just as nonarray variable names can. c[ a + b ] += 2; Image Credit: learningideasgradesk-8.blogspot.com
How To Declare An Array • Arrays occupy space in memory. • To specify the type of the elements and the number of elements required by an array use a declaration of the form: type arrayName[ arraySize ]; • The compiler reserves the appropriate amount of memory. (Recall that a declaration which reserves memory is more properly known as a definition.) • The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 12 elements for integer array c, use the declaration: int c[ 12 ]; // c is an array of 12 integers Image Credit: www.scholastic.com
How To Use An Array • Array access is extremely fast. • However, if you index past the end of the array, there is no safety net – you’ll step on other variables. • The other drawback is that you must define the size of the array at compile time; if you want to change the size at runtime you can’t do it. a[0] = 0 a[1] = 10 a[2] = 20 a[3] = 30 a[4] = 40 a[5] = 50 a[6] = 60 a[7] = 70 a[8] = 80 a[9] = 90 // File: Arrays.cpp #include <iostream> using namespace std; int main() { int a[10]; for(int i = 0; i < 10; i++) { a[i] = i * 10; cout << "a[" << i << "] = " << a[i] << endl; } }
In Class Programming Challenge: Seal Team 6 & Lakeland • You are part of a Seal team that has been ordered to go into zombie infested Lakeland and rescue a group of doctors at the hospital. • Lakeland is represented by a 20 x 20 two dimensional table that I have provided you with. • You are to write a program that will enter the Lakeland at location (19,0) (lower left- hand corner), work your way to the center to rescue the doctors, and then work your way out through the exit located at (0,0). You are to avoid all contact with zombies. Always move forward, never move behind you. Stop when you reach the extraction point. • A “cell” in the table that is infested with zombies contains a “1”. A clear cell has a “0”. A cell with the doctors has an “8”. • Every time your Seal team makes a move, print out the entire two dimensional table and show me where you are at by marking that cell with an “-”.
What’s In Your C++ Toolbox? cout / cin #include if/else/ Switch Math Class String getline While For do…While Break / Continue Arrays

Intro To C++ - Class #18: Vectors & Arrays

  • 1.
    An Introduction ToSoftware Development Using C++ Class #18: Vectors & Arrays
  • 2.
    Problems With YourHomework #2 “No hardcoding of a solution is permitted. Your program should be able to be run for any amount of time (e.g. two days) and produce the correct output for the entire time.”
  • 3.
    Thoughts On Homework#3: A Lot Of Subroutine Calls Return Addresses North South West East Main0 1 2 3 4 5 6 7 8 9 10 11 North South West East North South West East North South West Solution? Exit
  • 4.
    Thoughts On Homework#3: When To End? North South West East class Stoplight { private: startTime = time(0); } If (time(0) – startTime >= 60) exit;
  • 5.
    Thoughts On Homework#3: How To Handle The Emergency Vehicle North South West East 1. East is processing when the emergency vehicle arrives. 2. East passes control to West. 3. West commands everyone else to go to red and it goes to green. 4. West processes the emergency vehicle and then resumes normal operation.
  • 6.
    A Common Problem •A common problem in programming is not knowing how many of something you have while you’re writing a program – happens a lot. • The Standard C++ Library has a ready-made solution: the standard container classes. The container classes are one of the real powerhouses of Standard C++. Image Credit: drvidyahattangadi.com
  • 7.
    Say Hello ToVectors • A vector is a collection of objects, all of which have the same type. • Every object in the collection has an associated index, which gives access to that object. • A vector is often referred to as a container because it “contains” other objects. Image Credit: play.google.com
  • 8.
    How Do WeUse Vectors? • To use a vector, we must include the appropriate header. #include <vector> Image Credit: sivers.org
  • 9.
    Introducing Vectors • Thevector class is a template, which means that it can be efficiently applied to different types. • That is, we can create a vector of shapes, a vector of dogs, a vector of strings, etc. • Basically, with a template you can create a “class of anything.” • To tell the compiler what it is that the class will work with (in this case, what the vector will hold), you put the name of the desired type in “angle brackets,” which means ‘<’ and ‘>’. • So a vector of string would be denoted vector<string>. When you do this, you end up with a customized vector that will hold only string objects, and you’ll get an error message from the compiler if you try to put anything else into it. Image Credit: http://www.viralnova.com/crazy-xray-photos/3/
  • 10.
    All About Templates •A vector is a class template. • C++ has both class and function templates. • Templates are not themselves functions or classes. • Instead, they can be thought of as instructions to the compiler for generating classes or functions. • The process that the compiler uses to create classes or functions from templates is called instantiation. • When we use a template, we specify what kind of class or function we want the compiler to instantiate. Image Credit: www.digital-builder.co.uk
  • 11.
    How To InitializeA Vector vector<int> v1(10); // v1 has ten elements with value 0 vector<int> v2{10}; // v2 has one element with value 10 vector<int> v3(10, 1); // v3 has ten elements with value 1 vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1 Image Credit: support.radioshack.com
  • 12.
    How To InitializeA Vector • We can usually omit the value and supply only a size. • In this case the library creates a value-initialized element initializer for us. This library-generated value is used to initialize each element in the container. • The value of the element initializer depends on the type of the elements stored in the vector. • If the vector holds elements of a built-in type, such as int, then the element initializer has a value of 0. If the elements are of a class type, such as string, then the element initializer is itself default initialized: vector<int> ivec(10); // ten elements, each initialized to 0 vector<string> svec(10); // ten elements, each an empty string Image Credit: www.youtube.com
  • 13.
    Adding Things ToA Vector • Since vector expresses the concept of a “container,” there must be a way to put things into the container and get things back out of the container. • To add a brand-new element on the end of a vector, you use the member function push_back( ). • The. reason the name of this member function might seem a bit verbose – push_back( ) instead of something simpler like “put” – is because there are other containers and other member functions for putting new elements into containers. • For example, there is an insert( ) member function to put something in the middle of a container. • There’s also a push_front( ) (not part of vector) to put things at the beginning. Image Credit: blogs.courier-journal.com
  • 14.
    How Do YouGet Things Out Of A Vector? • So you can put new elements into a vector with push_back( ), but how do you get these elements back out again? We make the vector look like an array. • The array is a data type that is available in virtually every programming language so you should already be somewhat familiar with it. • Arrays are aggregates, which mean they consist of a number of elements clumped together. The distinguishing characteristic of an array is that these elements are the same size and are arranged to be one right after the other. • Most importantly, these elements can be selected by “indexing,” which means you can say “I want element number n” and that element will be produced, usually quickly. • Although there are exceptions in programming languages, the indexing is normally achieved using square brackets, so if you have an array a and you want to produce element five, you say a[4] (note that indexing always starts at zero). • This very compact and powerful indexing notation is incorporated into the vector. Image Credit: www.dynafile.com
  • 15.
    Sample Program: Print OutFile With Line Numbers// File Fillvector.cpp // Copy an entire file into a vector of string #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; int main() vector<string> v; ifstream in("18 Class 01 Fillvector.cpp"); string line; while(getline(in, line)) v.push_back(line); // Add the line to the end // Add line numbers: for(int i = 0; i < v.size(); i++) cout << i << ": " << v[i] << endl; } 0: // File Fillvector.cpp 1: // Copy an entire file into a vector of string 2: 3: #include <string> 4: #include <iostream> 5: #include <fstream> 6: #include <vector> 7: 8: #include <unistd.h> 9: #include <string.h> 10: 11: using namespace std; 12: 13: int main(){ 14: 15: vector<string> v; 16: 17: ifstream in("18 Class 01 Fillvector.cpp"); 18: string line; 19: 20: while(getline(in, line)) 21: v.push_back(line); // Add the line to the end 22: 23: // Add line numbers: 24: for(int i = 0; i < v.size(); i++) 25: cout << i << ": " << v[i] << endl; 26: 27: } stringobjects are pushed onto the back of the vector v Once the while loop completes, the entire file is resident in memory, inside v 1
  • 16.
    Sample Program: Place IntegersInto A Vector // File:Intvector.cpp // Creating a vector that holds integers #include <iostream> #include <vector> using namespace std; int main() { vector<int> v; for(int i = 0; i < 10; i++) v.push_back(i); for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; for(int i = 0; i < v.size(); i++) v[i] = v[i] * 10; // Assignment for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; } // end of main 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, You also have the ability to assign (and thus to change) to any element of a vector, also through the use of the square-brackets indexing operator. 2
  • 17.
    Vector In-Class Programming Assignment •Create a vector<float> and put 25 floating-point numbers into it using a for loop. – Display the vector. • Create three vector<float> objects and fill the first two as in the previous exercise. – Write a for loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vector. – Display all three vectors. • Create a vector<float> and put 25 numbers into it as in the previous exercises. – Now square each number and put the result back into the same location in the vector. – Display the vector before and after the multiplication. Image Credit: blog.intellisource.com
  • 18.
    Arrays • An arrayis a consecutive group of memory locations that all have the same type. • To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array. • This figure shows an integer array called c that contains 12 elements. You refer to any one of these elements by giving the array name followed by the particular element’s position number in square brackets ([]). • The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array). • The first element has subscript 0 (zero) [zero indexing] • Thus, the elements of array c are c[0] (pronounced “c sub zero”), c[1], c[2] and so on. • The highest subscript in array c is 11, which is 1 less than the number of elements in the array (12). Array names follow the same conventions as other variable names.
  • 19.
    Arrays • A subscriptmust be an integer or integer expression (using any integral type). • If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. • Example, if we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement: adds 2 to array element c[11]. • A subscripted array name is an lvalue—it can be used on the left side of an assignment, just as nonarray variable names can. c[ a + b ] += 2; Image Credit: learningideasgradesk-8.blogspot.com
  • 20.
    How To DeclareAn Array • Arrays occupy space in memory. • To specify the type of the elements and the number of elements required by an array use a declaration of the form: type arrayName[ arraySize ]; • The compiler reserves the appropriate amount of memory. (Recall that a declaration which reserves memory is more properly known as a definition.) • The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 12 elements for integer array c, use the declaration: int c[ 12 ]; // c is an array of 12 integers Image Credit: www.scholastic.com
  • 21.
    How To UseAn Array • Array access is extremely fast. • However, if you index past the end of the array, there is no safety net – you’ll step on other variables. • The other drawback is that you must define the size of the array at compile time; if you want to change the size at runtime you can’t do it. a[0] = 0 a[1] = 10 a[2] = 20 a[3] = 30 a[4] = 40 a[5] = 50 a[6] = 60 a[7] = 70 a[8] = 80 a[9] = 90 // File: Arrays.cpp #include <iostream> using namespace std; int main() { int a[10]; for(int i = 0; i < 10; i++) { a[i] = i * 10; cout << "a[" << i << "] = " << a[i] << endl; } }
  • 22.
    In Class ProgrammingChallenge: Seal Team 6 & Lakeland • You are part of a Seal team that has been ordered to go into zombie infested Lakeland and rescue a group of doctors at the hospital. • Lakeland is represented by a 20 x 20 two dimensional table that I have provided you with. • You are to write a program that will enter the Lakeland at location (19,0) (lower left- hand corner), work your way to the center to rescue the doctors, and then work your way out through the exit located at (0,0). You are to avoid all contact with zombies. Always move forward, never move behind you. Stop when you reach the extraction point. • A “cell” in the table that is infested with zombies contains a “1”. A clear cell has a “0”. A cell with the doctors has an “8”. • Every time your Seal team makes a move, print out the entire two dimensional table and show me where you are at by marking that cell with an “-”.
  • 23.
    What’s In YourC++ Toolbox? cout / cin #include if/else/ Switch Math Class String getline While For do…While Break / Continue Arrays

Editor's Notes

  • #2 New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.