Structured Data Types array array union union struct struct class class.
Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition...
-
Upload
aileen-wheeler -
Category
Documents
-
view
236 -
download
0
Transcript of Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition...
Lecture 26:Structures /structs/
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
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)
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.
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.
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/.
7
Struct definition (declaration)
OR
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/.
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.
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.
11
Struct definition (declaration)
struct specifier – no storage occupying sample
struct Person {char name[20];char gender;int age;float grade;
};
12
Struct definition (declaration)
OR
13
Struct definition (declaration)
Applying typedef reserved word
typedef struct
{
char name[20];
char gender;
int age;
float grade;
} Person;
14
Struct definition (declaration)
Member of the Person struct
char name[20]
can be replaced to
char *name or
string name
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;
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;
17
Initializing struct variables
Date today = { 28, 11, 2014 };
Person peter = {“Miller”, ‘m’, 19, 3.48 };
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;
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;
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);. . .
}
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 ;
}
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));. . . }
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:
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;
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;
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 = …
}
27
Pointers to Structs
struct Electricity
{
string current;
int volts;
};
Electricity *p, *q;
p and q are pointers to a struct of type Electricity
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
29
Assignments
*p.current = “AC”;*p.volts = 115;
Statements above can also be writtenp -> current = “AC”;p -> volts = 115;
AC 115current voltsp
30
Struct Member Access via Pointers
Form: p -> m Example: p -> volts
Example:– cout << p->current << p->volts <<endl;
Output– AC115
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
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
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.
34
More on structs
Extract from Friedman/Koffman, chapter 9
Data Structures Arrays and Structs
Chapter 9
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
37
Struct Employee
// Definition of struct employeestruct employee{ int id; string name; char gender; int numDepend; money rate; money totWages;};
38
Employee variables
// Definition of two struct employee variables
employee organist, janitor;
39
Anonymous struct
// Definition of anonymous struct
struct
{
int id;
string name;
char gender;
int numDepend;
money rate;
money totWages;
}
organist, janitor;
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
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;
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
43
Struct Copy or Assignment
struct copies
Given employee struct
employee organist, janitor;
organist = janitor;
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
45
ExamStat.h
// FILE: ExamStat.h
struct examStats
{
string stuName;
int scores[3];
float average;
char grade;
};
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;}
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
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.
49
Homework 6
Paper record to be presented before the end of next class
Tasks:– See .doc file.
50
Before lecture end
Lecture:
Structs
More to read:
Friedman/Koffman, Chapter 09
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
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
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;
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);
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
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
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)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 58
Listing 9.11 Function printStats
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 59
Listing 9.12 Function readEmployee
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
61
Thank You
For
Your Attention