more arrays arrays and classes multi-dimensional arrays dynamic arrays

Post on 21-Dec-2015

298 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

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

4/15/02

• Exam 3

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

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.

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

Declaring 2 Dimensional Arrays

• Declarationchar ticTacToe [3][3];

• Storage locationticTacToe [1][2]

Name Row Column

Example

const int Num_Rows = 11;

const int Seats_In_Row = 9;

string seatPlan [Num_Rows][Seats_In_Row];

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

Bigger Arrays

const int people = 10;

const int years = 5;

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

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]

4/17/02

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

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

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

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

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;

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;

4/19

• Design Exercise

• dynamic array class (section 1)

• command line arguments

• getline

• more on pointers

Command line arguments

g++ -o prog prog.cpp

Your programs can do this too

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

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 ...

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 ...

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 ...

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)

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

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

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)

char input

• reading into a char with >> skips whitespaces

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

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

Pointers

• Actual address has no meaning

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

?

P

new Operator

• Actually allocates storage

• Form: new type; // one memory location

new type [n]; // n memory locations

• Example: new double;

Pointer Variables

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

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

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

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

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

Pointers to Objects

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

Pointers to Structs

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

places address into pointer p

? ?current voltsp

Assignments

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

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

AC 115current voltsp

Struct Member Access via Pointers

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

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

• Output– AC115

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

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

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

Effect on new on the Heap

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;

top related