Presentation is loading. Please wait.

Presentation is loading. Please wait.

More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays.

Similar presentations


Presentation on theme: "More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays."— Presentation transcript:

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

2 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

3 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 4/15/02 Exam 3

5 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

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

7 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

8 Declaring 2 Dimensional Arrays Declaration charticTacToe [3][3]; Storage location ticTacToe [1][2] Name Row Column

9 Example const int Num_Rows = 11; const int Seats_In_Row = 9; string seatPlan [Num_Rows][Seats_In_Row];

10 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

11 Bigger Arrays const int people = 10; const int years = 5; money sales[people][years][12];

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 index matrix[2] wordList[1]

13 4/17/02

14 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

15 Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the address of an int; memory is allocated for the address (pointer) but not the int

16 Pointing to an existing int int i = 25; Allocates memory for an int and stores the valkue 25 int * iptr; Allocates memory for a pointer to an int iptr = & i; sets the value of iptr to the address of i i and *iptr are the same –changing either one will change the other

17 Creating a new int int j = 15; Allocates momory for an int and stores the value 15 int * 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

18 Pointers and Dynamic arrays A dynamic array is declared as a pointer int * iArray; use new to allocate appropriate amount of memory iArray = new int[ desiredSize]; use iArray just like you use any array iArray[index] = someValue;

19 Changing the size Allocate a new block of memory with new int *temp = new int[newSize]; Copy the elements in the current memory for (int j=0; j<currentSize; j++) temp[j] = iArray[i]; delete the old memory –delete [] iArray; reassign the pointer iarray = temp;

20 4/19 Design Exercise dynamic array class (section 1) command line arguments getline more on pointers

21 Command line arguments g++ -o prog prog.cpp Your programs can do this too

22 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

23 reading text Think of a filestream as a sequence of characters When you open the stream, the file pointer is at the beginning

24 reading with >> cin >> word => word = now cin >> word => word = is

25 reading with getline getline( cin, line) => line = " the time " getline( cin, line) => line = "for all good men"

26 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)

27 string Class used to store character strings #include string text; text = "a literal string"; cin >> text;// gets one word of text getline( cin, text);// gets to next newline

28 reading C-style strings char a[10]; cin >> a; whitespace delimited to read multiple words, use getline cin.getline( a, 10); the number is the number of elements in the array

29 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)

30 char input reading into a char with >> skips whitespaces if you need to get the space characters –istream::get( ch)

31 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

32 Pointers Actual address has no meaning Form:type*variable; Example: double *p; ? P

33 new Operator Actually allocates storage Form:new type; // one memory location new type [n]; // n memory locations Example:new double;

34 Pointer Variables If they aren't used for arrays, you have to use them differently

35 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

36 Pointer Statements double*p; p = new doublet; *p = 15.5; cout << “The contents of the memory cell pointed to by p is “ << *p << endl; Output The contents of memory cell pointed to by p is 15.5

37 Pointer Operations Pointers can only contain addresses So the following are errors: p = 1000; p = 15.5; You need to assign an address to p p = &varOfAppropriateType

38 Pointer Operations Assignment of pointers if q & p are the same pointer type q = 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

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

40 Pointers to Structs p = new electric; Allocates storage for struct of type electric and places address into pointer p ?? currentvoltsp

41 Assignments *p.current = “AC”; *p.volts = 115; Statements above can also be written –p ->current = “AC”; –p ->volts = 115; AC115 currentvoltsp

42 Struct Member Access via Pointers From:p ->m Example:p ->volts Example: –cout current volts << endl; Output –AC115

43 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; AC115 q->currentq->voltsq

44 Pointers to Objects q->volts = 220; q = p; AC220 q->currentq->voltsq AC 115 AC220 q pq->currentq->volts p->currentp->volts

45 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

46 Effect on new on the Heap

47 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:deletevariable; Example:deletep;


Download ppt "More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays."

Similar presentations


Ads by Google