more arrays arrays and classes multi-dimensional arrays dynamic arrays

47
More Arrays • Arrays and classes • Multi-dimensional Arrays • Dynamic arrays

Post on 21-Dec-2015

297 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

More Arrays

• Arrays and classes

• Multi-dimensional Arrays

• Dynamic arrays

Page 2: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Arrays and classes

• You can have arrays of objects– element class - use array of elements to store data

needed for amino acid program– Money class - use an array of Money objects to store all

the prices for a customer

• You can have arrays inside classes– a Molecule class could have an array of all the elements

in the molecule– an Inventory class could have an array of all the items

stocked by a store

Page 3: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Arrays vs classes

• Sometimes you can accomplish the same thing easier with classes– nX3 array of numbers to represent a series of

cartesian points– 1-D array of 3D_point objects

• Parallel arrays vs array of objects– arrays of objects easier to keep data todgether

Page 4: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

4/15/02

• Exam 3

Page 5: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Why multiple dimensions

• Sometimes it is useful to have arrays of more than one dimension. – a game program that used a checkerboard:

represent the squares as elememts of a 2D array– array of words, you could use a 2-D array of

char

Page 6: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Multi-D arrays

• Think of 2-D arrays as arrays of a particular kind of 1-D array. – The first index tells you how many of these 1-D

arrays you are declaring, – the second index gives the the size these 1-D

arrays.

• 3-D arrays are arrays of 2_D arrays, etc.– more than two or three dimensions not

common.

Page 7: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Declaring 2-D arrays

• similar to one dimensional arrays.int matrix[8][6]; – declares an 8 by 6 array of ints, i.e. an array of

8 6-element arrays

char wordList[10][20]; – declares an array of 10 cstrings, each of which

can have 19 characters

Page 8: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Declaring 2 Dimensional Arrays

• Declarationchar ticTacToe [3][3];

• Storage locationticTacToe [1][2]

Name Row Column

Page 9: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Example

const int Num_Rows = 11;

const int Seats_In_Row = 9;

string seatPlan [Num_Rows][Seats_In_Row];

Page 10: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Initialization

const int Num_Rows = 2;

const int Num_Cols = 3;

float matrix[Num_Rows][Num_Cols] ={{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}};

• Nested loops with two-dimensional arrays• SumMatrx.cpp example

Page 11: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Bigger Arrays

const int people = 10;

const int years = 5;

money sales[people][years][12];

Page 12: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Accessing elements

• access single elements with indices just the same way as you do those of 1-D arrays,matrix[2][3] wordList[1][5]

• access a single "row" with a single indexmatrix[2] wordList[1]

Page 13: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

4/17/02

Page 14: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Dynamic Arrays

• Arrays we have looked at so far are static - size is fixed

• sometimes you don't know how many elements you will need

• To understand dynamic arrays, we need to understand pointers

Page 15: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointer Variables

int i;

• declares an int variable and sets aside a named memory location to store the intint * iptr;

• declares a variable that holds the address of an int; memory is allocated for the address (pointer) but not the int

Page 16: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointing to an existing int

int i = 25;

• Allocates memory for an int and stores the valkue 25int * iptr;

• Allocates memory for a pointer to an intiptr = & i;

• sets the value of iptr to the address of i• i and *iptr are the same

– changing either one will change the other

iptr

i25

iptri25

Page 17: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Creating a new int

int j = 15;

• Allocates momory for an int and stores the value 15int * jptr; = new int;

• sets aside memory for an int and puts the address int j*j = j;

• stores value of j in memory pointed to by jptr

j15

jptr

15jptr j15

Page 18: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointers and Dynamic arrays

• A dynamic array is declared as a pointerint * iArray;

• use new to allocate appropriate amount of memoryiArray = new int[ desiredSize];

• use iArray just like you use any arrayiArray[index] = someValue;

Page 19: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Changing the size

• Allocate a new block of memory with newint *temp = new int[newSize];

• Copy the elements in the current memoryfor (int j=0; j<currentSize; j++)

temp[j] = iArray[i];

• delete the old memory– delete [] iArray;

• reassign the pointeriarray = temp;

Page 20: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

4/19

• Design Exercise

• dynamic array class (section 1)

• command line arguments

• getline

• more on pointers

Page 21: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Command line arguments

g++ -o prog prog.cpp

Your programs can do this too

Page 22: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

use a different prototype for main

int main( int argc, char ** argv) {...}

• argc is the number of "words" in the command line (space delimited) including the name of the program

• argv is a 2-D array of char – uses pointer notation

Page 23: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

reading text

• Think of a filestream as a sequence of characters

• When you open the stream, the file pointer is at the beginning

Now is the time \n for all good men\nto come ...

Now is the time \n for all good men\nto come ...

Page 24: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

reading with >>

• cin >> word => word = now

• cin >> word => word = is

Now is the time \n for all good men\nto come ...

Now is the time \n for all good men\nto come ...

Now is the time \n for all good men\nto come ...

Page 25: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

reading with getline

• getline( cin, line) => line = " the time "

• getline( cin, line) =>

line = "for all good men"

Now is the time \n for all good men\nto come ...

Now is the time \n for all good men\nto come ...

Now is the time \n for all good men\nto come ...

Page 26: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Using operator>> and getline

• Behavior is basically the same for C-style strings (char arrays) and string objects

• there are two overloaded versions of getline– void istream::getline( char[], int)– void getline(istream &, string)

Page 27: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

string Class

• used to store character strings#include <string>

string text;

text = "a literal string";

cin >> text; // gets one word of text

getline( cin, text); // gets to next newline

Page 28: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

reading C-style strings

char a[10];cin >> a;

• whitespace delimited

• to read multiple words, use getlinecin.getline( a, 10);

the number is the number of elements in the array

Page 29: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

getline with delimiters

• You may sometimes have data separated by other characters than the newline– spreadsheet and database programs will usually

print out tab or comma separated text

• two versions of getline allow you to specify the delimiter– void istream::getline( char[], int, char)– void getline(istream &, string, char)

Page 30: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

char input

• reading into a char with >> skips whitespaces

• if you need to get the space characters– istream::get( ch)

Page 31: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointers and the “new” Operator

• Pointer Declarations– pointer variable of type “pointer to double”– can store the address of a double t in p

double *p;

• The new operator creates a variable of type double & puts the address of the variable in pointer p

p = new double;

• Dynamic allocation - memory is allocated while the program is running instead of before it starts

Page 32: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointers

• Actual address has no meaning

• Form: type *variable;• Example: double *p;

?

P

Page 33: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

new Operator

• Actually allocates storage

• Form: new type; // one memory location

new type [n]; // n memory locations

• Example: new double;

Page 34: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointer Variables

• If they aren't used for arrays, you have to use them differently

Page 35: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Accessing Data with Pointers

• * - indirection operator*p = 15.5;

• Stores floating value 15.5 in memory location *p - the location pointed to by p

15.5

p

Page 36: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointer Statements

double *p;

p = new doublet;

*p = 15.5;

cout << “The contents of the memory cell pointed to by p is “ << *p << endl;

OutputThe contents of memory cell pointed to by p is 15.5

Page 37: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointer Operations

• Pointers can only contain addresses

• So the following are errors:p = 1000;

p = 15.5;

• You need to assign an address to pp = &varOfAppropriateType

Page 38: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointer Operations

• Assignment of pointers if q & p are the same pointer typeq = p;• p and q both refer to the same memeory

location - tha same variable

• relational operations == and != compare addresses not the values stored at those addresses

Page 39: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointers to Objects

class electric {public: string current; int volts;};electric *p, *q;• p and q are pointers to objects of type electric

Page 40: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointers to Structs

p = new electric;• Allocates storage for struct of type electric and

places address into pointer p

? ?current voltsp

Page 41: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Assignments

*p.current = “AC”;*p.volts = 115;

• Statements above can also be written– p ->current = “AC”;– p ->volts = 115;

AC 115current voltsp

Page 42: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Struct Member Access via Pointers

• From: p ->m• Example: p ->volts

• Example:– cout << p->current << p->volts << endl;

• Output– AC115

Page 43: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointers to Objects

q = new electric;• Allocates storage for object of type electric and

places address into pointer q• Copy contents of p struct to q struct

*q = *p;

AC 115

q->current q->voltsq

Page 44: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Pointers to Objects

q->volts = 220;

q = p;

AC 220

q->current q->voltsq

AC 115

AC 220

q

p q->current q->voltsp->current p->volts

Page 45: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

13.2 Manipulating the Heap

• When new executes where is struct stored ?

• Heap– C++ storage pool available to new operator

• Effect of p = new node;

• Figure 14.1 shows Heap before and after executing new operator

Page 46: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Effect on new on the Heap

Page 47: More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays

Returning Cells to the Heap

• Operation– delete p;

• Returns cells back to heap for re-use• When finished with a pointer delete it• Watch dual assignments and initialization

• Form: delete variable;• Example: delete p;