lecture 26: structures / struct s/. 2 lecture contents: t basics of structs t struct type definition...

61
Lecture 26: Structures /structs/

Upload: aileen-wheeler

Post on 13-Jan-2016

236 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Lecture 26:Structures /structs/

Page 2: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

2

Lecture Contents:

Basics of structs Struct type definition (struct reserved word) Struct type definition (typedef statement) Structs and functions Structs as input parameters and return values Arrays of structs Pointers to structs Demo programs Exercises

Page 3: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

3

Reminder on data structs

Data structure: composite of related data items stored in memory under the same name.

Typical data structures available in most PL:– Array: already discussed – Structure: to discuss today (same as record in Pascal)

– Class: structure with functions /methods/ (OOP)– File (I/O processing aside keyboard and screen)

Page 4: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

4

Reminder on arrays

Array: a collection of data items of the same type.

Reminder:

Simple data type: Data type used to store a single value.

scalar variable stores a single value.

Therefore array may store many data items of the same type.

Page 5: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

5

Basics of structures

Definition: A collection of simple variables.

A data type for a record composed of multiple components. These components may be the same data type or may be not the same data type.

Page 6: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

6

Struct definition (declaration)

struct specifier – applying struct reserved word.

struct Date

{

int day, month, year;

};

This is a template only which does not occupy storage /memory cells/.

Page 7: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

7

Struct definition (declaration)

OR

Page 8: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

8

Struct definition (declaration)

Applying typedef statement

typedef struct { int day, month, year; } Date;

This is a template only which does not occupy storage /memory cells/.

Page 9: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

9

The struct template

The struct template has to be globally defined.

It is recommended The struct template to be typed outside any function body.

Globally defined struct template makes it visible in all functions that follow the definition.

Page 10: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

10

Basics of structs

Arrays are data structures to store a collection of data items of the same type.

Structs as opposed to arrays, are data structures to store collections of related data items that have different types.

The individual component of a struct is called a member.

Page 11: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

11

Struct definition (declaration)

struct specifier – no storage occupying sample

struct Person {char name[20];char gender;int age;float grade;

};

Page 12: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

12

Struct definition (declaration)

OR

Page 13: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

13

Struct definition (declaration)

Applying typedef reserved word

typedef struct

{

char name[20];

char gender;

int age;

float grade;

} Person;

Page 14: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

14

Struct definition (declaration)

Member of the Person struct

char name[20]

can be replaced to

char *name or

string name

Page 15: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

15

Referencing a struct type

How to define a struct as a variable to be a scalar, an array or a pointer?

Date a, b;

Date c[20];

Date *ptr1;

Page 16: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

16

Referencing a struct type

How to define a struct as a variable to be a scalar, an array or a pointer?

Person John, Mary;

Person ClassCos120a[20];

Person ClassCos120b[17];

Person *ptr2;

Page 17: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

17

Initializing struct variables

Date today = { 28, 11, 2014 };

Person peter = {“Miller”, ‘m’, 19, 3.48 };

Page 18: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

18

Accessing struct members

Date a, b, c[20], *ptr1;

Direct component selection operator . (period)

a.day=28;

b.month=11;

c[10].year=2014;

Indirect component selection operator ─>

ptr1 = &a; ptr1─>month = 4;

Page 19: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

19

Structs within structs

struct Dimension{ int feet; float inches; };

struct Room { Dimension length, width; };

Room kitchen; kitchen.length.feet = 12; kitchen.length.inches = 2.4; kitchen.width.feet = 10; kitchen.width.inches = 1.8;

Page 20: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

20

Functions returning structs struct Point { int x; int y; };

Point makepoint(int xvar, int yvar) { Point temp; temp.x = xvar;temp.y = yvar; return temp;

}

void main() { Point a, b;

a = makepoint(0,0);b = makepoint(350,200);. . .

}

Page 21: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

21

Passing struct variables as arguments to functions

struct Point { int x; int y; };

struct Rect { Point pt1, pt2; };

Pt1 – top left corner

Pt2 – bottom right corner

bool isPtinRect(Point p, Rect r)

{

return p.x>=r.pt1.x && p.x<=r.pt2.x &&

p.y>=r.pt1.y && p.y<=r.pt2.y ;

}

Page 22: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

22

Functions with structs as arguments returning structs

struct Point { int x; int y; }; Point addpoint( Point p1, Point p2) {

Point temp; // alternate versiontemp.x = p1.x + p2.x; // p1.x = p1.x + p1.y;temp.y = p1.y + p2.y; // p1.y += p2.y;return temp; // return p1;

} void main() { Point a, b, c; a=makepoint(0,0);

b=makepoint(40, 20); c=addpoint(b,makepoint(20, 40));. . . }

Page 23: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

23

Parallel arrays and arrays of structs

Problem: data base for COS120 students

Solution based on parallel arrays:

Alternate solution: based on array of structures:

Page 24: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

24

Parallel arrays and arrays of structs

Problem: data base for COS120 students Solution based on parallel arrays:

char *name[20]; int id[20]; double gpa[20];

Three parallel arrays because data items with same subscript pertain the same student name[I] = “Peter”;

id[I] = 0100245678;gpa[I] = 3.68;

Page 25: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

25

Parallel arrays and arrays of structs

Problem: data base for COS120 students Alternate solution: based on array of structs:

struct Stud{char *name; int id; double gpa;};

Stud ar[20];

. . .

ar[I].name = “Peter”;

ar[I].id = 0100245678;

ar[I].gpa = 3.68;

Page 26: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

26

Pointers to structs

struct Person { char *name, gender; int age;};

Person Mary, family[5], *ps; for (ps=family; ps<family+5; ps++) // or for (ps=&family[0]; ps<=&family[4]; ps++) {

(*ps).name = … or ps->name = …(*ps).gender = … or ps->gender = …(*ps).age = … or ps->age = …

}

Page 27: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

27

Pointers to Structs

struct Electricity

{

string current;

int volts;

};

Electricity *p, *q;

p and q are pointers to a struct of type Electricity

Page 28: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

28

Pointers to Structs

p = new Electricity; Allocates storage for struct of type

Electricity and places address into pointer p

Struct access operator .

? ?current voltsp

Page 29: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

29

Assignments

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

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

AC 115current voltsp

Page 30: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

30

Struct Member Access via Pointers

Form: p -> m Example: p -> volts

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

Output– AC115

Page 31: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

31

Pointers to Structs

q = new Electricity; Allocates storage for struct of type Electricity and

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

*q = *p;

AC 115

q->current q->voltsq

Page 32: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

32

Pointers to Structs

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 33: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

33

Unions

A data structure that overlays components in memory, allowing one chunk of memory (the same memory cell or memory cells with same initial address) to be interpreted in multiple ways.

Page 34: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

34

More on structs

Extract from Friedman/Koffman, chapter 9

Page 35: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Data Structures Arrays and Structs

Chapter 9

Page 36: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

36

9.7 The Struct Data Type

struct used to store related data items Individual components of the struct are

called its members Each member can contain different types of

data Employee example

Page 37: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

37

Struct Employee

// Definition of struct employeestruct employee{ int id; string name; char gender; int numDepend; money rate; money totWages;};

Page 38: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

38

Employee variables

// Definition of two struct employee variables

employee organist, janitor;

Page 39: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

39

Anonymous struct

// Definition of anonymous struct

struct

{

int id;

string name;

char gender;

int numDepend;

money rate;

money totWages;

}

organist, janitor;

Page 40: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

40

Accessing Members of a struct

Members are accessed using the member access operator, a period

For struct variable s and member variable m to access m you would use the following:– cout << s.m << endl;

Can use all C++ operators and operations on structs

Page 41: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

41

Accessing Members of a struct

organist.id = 1234;

organist.name = “Noel Goddard”;

organist.gender = ‘F’;

organist.numDepend = 0;

organist.rate = 6.00;

organist.totWages += organist.rate * 40.0;

Page 42: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

42

9.8 Structs as Operands and Arguments

How to do arithmetic and other operations using structs

Process entire struct using programmer defined functions

Often better to pass an entire struct rather than individual elements

Page 43: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

43

Struct Copy or Assignment

struct copies

Given employee struct

employee organist, janitor;

organist = janitor;

Page 44: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

44

Passing struct as an Argument

Grading program example Keep track of students grades Prior to our learning structs we needed to

store each item into a single variable Group all related student items together Pass struct by const reference if you do not

want changes made

Page 45: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

45

ExamStat.h

// FILE: ExamStat.h

struct examStats

{

string stuName;

int scores[3];

float average;

char grade;

};

Page 46: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

466

PrintStats.cpp

// File: printStats.cpp Prints the exam statistics// Pre: The members of the struct variable// stuExams are assigned values.// Post: Each member of stuExams is displayed.

void printStats(examStats stuExams) { cout << "Exam scores for " <<stuExams.stuName << ":\n“; cout << stuExams.scores[0] << ' ' <<

stuExams.scores[1] << ' ' << stuExams.scores[2] << endl;

cout << "Average score: " <<stuExams.average << endl; cout << "Letter grade : " << stuExams.grade << endl;}

Page 47: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

47

Common Programming Errors

No prefix to reference a struct member Incorrect prefix reference to a struct

member Missing ; following definition of struct Initialization of struct members

Page 48: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

48

Exercise 26.1-26.7

Build programs based on structs: Create a struct named Date to include three components all of int type – Day, Month and Year. Define

three Date variables – D1, D2 and D3. D1 to be initialized. Load values for D2 using assignment statements and values for D3 entering input data from the keyboard. Display on the screen all members of the struct variables D1, D2, D3.

Create a struct named Time to include three components all of int type – Hrs, Mins and Scnds. Define three Time variables – T1, T2 and T3. T1 to be initialized. Load values for T2 using assignment statements and values for T3 entering input data from the keyboard. Display on the screen all members of the struct variables T1, T2, T3.

Create a struct named Person with data members for name, gender and age. Define struct variables describing data for your family.

Create a struct named Employee with data members for name, position and salary. Define struct variables describing data for five officers.

Create a struct named Student with data members for name, id# and e-mail address. Define struct variables describing data for your friends.

Create a struct to describe a 2D point in polar coordinates. Create a struct to describe a 3D point in rectangular coordinates.

Page 49: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

49

Homework 6

Paper record to be presented before the end of next class

Tasks:– See .doc file.

Page 50: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

50

Before lecture end

Lecture:

Structs

More to read:

Friedman/Koffman, Chapter 09

Page 51: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 9:Data Structs: Arrays and Structs

Problem Solving,

Abstraction, and Design using C++ 5e

by Frank L. Friedman and Elliot B. Koffman

Page 52: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 52

9.7 The struct Data Type

• struct used to store related data items • Individual components of the struct are called its

members• Each member can contain different types of data• Three parts

– declaration of struct

– use of struct to define a new variable

– access of members of the structd variable

• Typically declare struct as global

Page 53: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 53

struct Type Declaration

struct struct-type

{

type1 id-list1;

type2 id-list2;

. . .

typen id-listn;

};

struct employee

{

int id;

string name;

char gender;

int numDepend;

float rate;

float totWages;

};

. . .

employee organist, janitor;

Page 54: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 54

Accessing Members of a struct

organist.id = 1234;

organist.name = “Noel Goddard”;

organist.gender = ‘F’;

organist.numDepend = 0;

organist.rate = 12.00;

organist.totWages = 480.0;

. . .

organist.totWages += (organist.rate * 40.0);

Page 55: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 55

9.8 structs as Operands and Arguments

• struct copy or assignment

organist = janitor; // copy janitor to organist

• Copies each member from janitor struct to organist struct

Page 56: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 56

Passing a struct as an Argument

• Actual and formal parameters must be same type struct

• Using structs as arguments can shorten argument list

• Passing structs by value can be inefficient, since it duplicates values of all members

Page 57: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 57

Passing struct by Reference

• Same as other reference parameters– use & to identify in parameter list

• Can also use constant reference– precede parameter with reserved word const– E.g.

void printStats(const examStats& stuExams)

Page 58: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 58

Listing 9.11 Function printStats

Page 59: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 59

Listing 9.12 Function readEmployee

Page 60: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 60

9.10 Common Programming Errors

• structs– References to a struct member with no prefix– Reference to a struct member no incorrect

prefix– Missing semicolon following a struct

declaration

Page 61: Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition

61

Thank You

For

Your Attention