Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan...

46
Chapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College

Transcript of Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan...

Page 1: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Chapter 07

Arrays and Vectors

Fall 2020The Borough of Manhattan

Community College

Page 2: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays Hold Multiple Values

•Array: a variable that can store multiple values of

the same type

•The values are stored in consecutive memory

locations

• It is declared using [] operator

const int ISIZE = 5;

int tests[ISIZE];

Page 3: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Array Storage in Memory

The definitionint tests[ISIZE]; // ISIZE is 5

allocates the following memory

Page 4: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Accessing Array Elements

Array elements (accessed by array name and

subscript) can be used as regular variables

tests[0] = 79;cout << tests[0];cin >> tests[1];tests[4] = tests[0] + tests[1];

cout << tests; // illegal due to// missing subscript

Page 5: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Accessing All Array Elements

To access each element of an array

–Use a loop

–Use the loop control variable as the array

subscript

–A different array element will be referenced each time through the loop

for (i = 0; i < 5; i++)

cout << tests[i] << endl;

Page 6: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Array Initialization

•An array can be initialized during program execution with assignment statements

tests[0] = 79;

tests[1] = 82; // etc.

• It can be initialized at array definition with an initialization listconst int ISIZE = 5;

int tests[ISIZE] = {79,82,91,77,84};

Page 7: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Partial Array Initialization

• If a numerical array is initialized at definition with fewer values than the size declarator of the array, the remaining elements will be set to 0

int tests[5] = {79,82};

• Initial values are used in order; you cannot skip over elements to initialize a noncontiguous range

•You cannot have more values in the initialization list than the declared size of the array

Page 8: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Implicit Array Sizing

•C++ can determine the array size by the size of

the initialization list

short quizzes[]={12,17,15,11};

•You must use either an array size declarator or

an initialization list when the array is defined

Page 9: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Copying One Array to Another

•You cannot copy with an assignment statement:

tests2 = tests; //won’t work

•You must instead use a loop to copy element-by-

element:

for (int i = 0; i < ISIZE; i++)

tests2[i] = tests[i];

Page 10: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

The Range-Based for Loop

• C++ 11 provides a specialized version of the for loop

that, in many circumstances, simplifies array processing.

• The range-based for loop is a loop that iterates once for

each element in an array.

• Each time the loop iterates, it copies an element from the

array to the range variable.

• The range-based for loop automatically knows the

number of elements in an array; so you do not have to

use a counter variable.

Page 11: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

The Range-Based for Loop

• Here is the general format of the range-based for loop:

for (dataType rangeVariable : array)

statement;

- dataType is the data type of the range variable.

- rangeVariable is the name of the range variable. This variable

will receive the value of a different array element during each loop

iteration.

- array is the name of an array on which you wish the loop to

operate.

- statement is a statement that executes during a loop iteration. If

you need to execute more than one statement in the loop, enclose the

statements in a set of braces.

Page 12: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

The range-based for loop in Program 7-10

Page 13: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Modifying an Array with a Range-Based

for Loop

•As the range-based for loop executes, its range

variable contains only a copy of an array

element.

•You cannot use a range-based for loop to

modify the contents of an array unless you

declare the range variable as a reference.

•To declare the range variable as a reference variable, simply write an ampersand (&) in front

of its name in the loop header.

Page 14: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

const int SIZE = 5;

int numbers[5];

// Get values for the array.

for (int &val : numbers)

{

cout << "Enter an integer value: ";

cin >> val;

}

// Display the values in the array.

cout << "Here are the values you entered:\n";

for (int val : numbers)

cout << val << endl;

Modifying an Array with a Range-Based

for Loop in Program 7-12

Page 15: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Using Parallel Arrays

•Parallel arrays: two or more arrays that contain related data

•The subscript is used to relate the arrays

– elements at the same subscript are related

•The arrays do not have to hold data of the same type

Page 16: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Parallel Array Example

const int ISIZE = 5;

string name[ISIZE]; // student name

float average[ISIZE]; // course average

char grade[ISIZE]; // course grade

Page 17: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Parallel Array Processing

for (int i = 0; i < ISIZE; i++)

cout << " Student: " << name[i]

<< " Average: " << average[i]

<< " Grade: " << grade[i]

<< endl;

Page 18: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays as Function Arguments

•To define a function that has an array parameter, use empty [ ] to indicate the array in the prototype and header

// Function prototypevoid showScores(int[]);

// Function headervoid showScores(int A[])

•To pass an array to a function, just use the array name without any brackets

// Function callshowScores(tests);

Page 19: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

•You can also pass the array size as a separate

parameter so the function knows how many

elements to process

void showScores(int[], int); // prototype

void showScores(int A[],int size) // header

showScores(tests,5); // call

Arrays as Function Arguments

Page 20: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Passing an Array to a Function in Program 7-17

Page 21: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Modifying Arrays in Functions

•Array parameters in functions are similar to reference variables

•Changes made to an array passed to a

function are made to the actual array in the

calling function

•The const keyword can be used in the prototype and header to prevent changes

void showScores(const int[],int); // prototype

void showScores(const int A[],int size) // header

Page 22: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Two-Dimensional Arrays

•A two-dimensional array is like several

identical arrays put together. It is like a table in

a spreadsheet

•Use two size declarators in definition

int exams[4][3];

// first [] is the number of rows

// second [] is the number of columns

Page 23: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Two-Dimensional Array Representation

int exams[4][3];

Use two subscripts to access an element

exams[2][1] = 86;

Page 24: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Initialization at Definition

• Two-dimensional arrays are initialized row-by-row

int exams[2][2] = {{84,78},{92,97}};

• The inner { } in the initialization improve readability but

are not required

• The inner { } can be used to initialize some but not all

elements of a two-dimensional array

int table[3][2] = {{1},{3,4},{5}};

• The uninitialized elements (in this case table[0][1] and table[2][1]) are automatically set to zero

Page 25: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Two-Dimensional Array Traversal

•Use nested loops, one for the row and one for

the column, to visit each array element.

•Accumulators can be used to calculate the sum

of the elements row-by-row, column-by-column,

or over the entire array.

Page 26: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple
Page 27: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Passing a Two-Dimensional Array to a

Function

•Use empty [] for row and a size declarator for the number of columns in the prototype and header

// Prototype void getExams(int[][NUM_COLS], int);

// Headervoid getExams(int exams[][NUM_COLS], int rows)

•Use the array name and the number of rows as arguments in the function call

getExams(exams,25);

Page 28: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple
Page 29: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Passing a Two-Dimensional Array to a

Function

• C++ needs the size declarator for the number of columns to correctly translate a subscripted array reference, such as table[2][1], to the address in memory where that element is stored

• The way two-dimensional arrays are stored in memory is: One row follows another

Page 30: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays with Three or More Dimensions

•You can define arrays that have any number of dimensions

double seat[3][5][8];

Page 31: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays with Three or More Dimensions

•Arrays with more than three dimensions are difficult to visualize

double timeGrid[5][52][7][24];

•When this type of array is used as a parameter,

specify the size of all but the 1st dimension

void displaySeats(double[][5][8]);

Page 32: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays of Objects

•Objects can be used as array elements class Square

{ private:

int side;

public:

Square(int s = 1)

{ side = s; }

int getSide()

{ return side; }

};

Square shapes[10]; // Create array of 10

// Square objects

Page 33: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays of Objects

•Use the array subscript to access a specific object

in the array

•Then use dot operator to access the member

methods of that object

for (i = 0; i < 10; i++)

cout << shapes[i].getSide() << endl;

Page 34: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Initializing Arrays of Objects

•You can use the default constructor to perform the same initialization for all objects

•You can use an initialization list to supply specific initial values for each object

Square shapes[5] = {1,2,3,4,5};

•The default constructor is used for the remaining objects if initialization list is too short

Square boxes[5] = {1,2,3};

Page 35: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Initializing Arrays of Objects

• If an object is initialized with a constructor that takes > 1 argument, the initialization list should include a call to the constructor for that object

Rectangle spaces[3]={ Rectangle(2,5),

Rectangle(1,3),

Rectangle(7,7)

};

•The same constructor does not have to be used for every object that is being initialized

Page 36: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays of Structures

•Structures can be used as array elements

struct Student{int studentID;string name;short year;double gpa;

};

Student class[30]; // Holds 30// Student structures

•An array of structures can be used as an alternative

to parallel arrays

Page 37: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Arrays of Structures

•Use the array subscript to access a specific

structure in the array

•Then use the dot operator to access members of

that structure

cin >> class[25].studentID;

cout << class[i].name << " has GPA "

<< class[i].gpa << endl;

Page 38: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Introduction to Vectors

•A vector holds a sequence of elements, like a one-dimensional array

• Its size is flexible. It can grow and shrink–There is no need to specify the size when defined

–Space is automatically added as needed

•Must include vector header file to use vectors

#include <vector>

Page 39: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Vectors

• It can hold values of any data type, specified when

the vector is defined

vector<int> scores;

vector<double> volumes;

•You can specify initial size if desired

vector<int> scores(24);

•You can use [] to access individual elements

Page 40: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Defining Vectors

•Define a vector of integers (starts with 0 elements)

vector<int> scores;

•Define int vector with initial size 30 elements

vector<int> scores(30);

•Define 20-element int vector and initialize all elements to 5

vector<int> scores(20,5);

Page 41: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

•Define int vector initialized to size and contents of another vector: scores

vector<int> finals(scores);

•C++ 11 supports vector definitions that use an initialization list

vector<int> scores {88,67,79,84};

Note: No “=“ operator between the vector name and the initialization list

Defining Vectors

Page 42: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Growing a Vector’s Size

•Use the push_back member function to add an element to a full vector or to a vector that had no defined size

// Add a new element holding the value 75

scores.push_back(75);

•Use the size member function to determine the number of elements currently in a vector int howbig = scores.size();

Page 43: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Growing a Vector’s Size

Page 44: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Removing Vector Elements

•Use the pop_back member function to remove the last element from a vector

scores.pop_back();

Note: pop_back removes the last element but does not return it

•To remove all of the elements from a vector, use the clear member function

scores.clear();

•To determine if a vector is empty, use emptymember function

while (!scores.empty()) ...

Page 45: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Using the Range-Based for Loop with a vector

Page 46: Arrays and Vectors - WeeblyChapter 07 Arrays and Vectors Fall 2020 The Borough of Manhattan Community College. Arrays Hold Multiple Values •Array: a variable that can store multiple

Other Useful Member Functions

Member Function

Description Example

at(i) Returns the value of the element at position i in the vector

cout << vec1.at(i);

capacity() Returns the maximum number of elements a vector can store without allocating more memory

maxElements = vec1.capacity();

reverse() Reverse the order of the elements in a vector

vec1.reverse();

resize(n,val)

Resizes the vector so it contains nelements. If new elements are added, they are initialized to val

vec1.resize(5,10);

swap(vec2) Exchange the contents of two vectors

vec1.swap(vec2);