Upload
cody-allen
View
239
Download
2
Embed Size (px)
Citation preview
Structured Data Types
structclass
Structured Data Types
array – homogeneous container collections of only one type
struct – heterogeneous data type collections of different types
Structured Data Types
struct is a user defined data type with a fixed number of components that are accessed by name, not by index.Each component is called a field or a member
Structure Declaration
struct MyDateType {int month; int day; int year;
};for above, the struct members are month, day, and year
struct TAG
Representation in Memorymonth day year
struct Employee {
int id;
char name[15]
double salary;
};
Employee Emp1 = {1234, “Smith”, 5.6};
id name salary
001234 S m i t h \0 5.6
each cell represents 1 byte,
so an int is stored in 4 bytes, name has
15 bytes reserved
and salary is a double 8 bytes
members can be arrays! or other structs!
Structure declaration specifying a template like creating your own datatype
Object declaration or variable declaration or object instantiation using your own data type
Object Declaration/Instantiation
int num;double x;
MyDateType myBirth, today, tomorrow;
data type variable name
Declaration and Initialisation
Date myBirth = {4, 2, 1980};
Date today = {11, 25, 1999};
Date tomorrow = {3, 25,
2001};
Assigning Values
myBirth = {4, 2, 1980};
today = {11, 25, 1999};
tomorrow = {3, 25, 2001};
Illegal !
Legal !
myBirth = today;
Assigning ValuesmyBirth.month = 4;myBirth.day = 2;myBirth.year =
1980;
today.month = 3;today.day = 25;today.year = 1995;
instance of DateType
member of myBirth instance
Note dot, This is the member selection
operator
Accessing struct Values
// to assign to a basic variableyear = today.yearnew_mo = today.month + 1
// to assign contents of a variable to a structure member
today.month = someMonth;
keyboard inputDate today, bill_date;
cout << “Enter month, day and year: “;cin >> today.month >>today.day >> today.year;
bill_date = today; // an aggregate action
cout << bill_date.month <<“ “ << bill_date.day;
it should be easy to see how you can read from a file
Structures used as function arguments
int Overdue(Date now, int purchaseyear); Overdue(today, bill_Date.year);
int Overdue(Date &now, int purchaseyear);Overdue(today, bill_Date.year);
Pass by value
Pass by reference
Pass by value and Pass by reference
The same rules apply to structure objects as to basic atomic data.You can pass a structure by value, the argument passes a copy of individual members to the receiving parameter. in previous slide the argument today was
copied to parameter now.
You can specify the function to pass by reference by use of the reference symbol &.
Aggregate Operations
Operation ArraysStructsI/O No (except strings) NoAssignment No YesArithmetic No NoComparison No NoParameter pass. Ref. only Either
value or ref.
Funct. return value No Yes
Arrays of Structures
struct PrisonerRecord{ char lastName[20];char firstName[20];char Occupation[20];char MaritalStatus[20];int age;char BirthPlace[20];
};
// array of 100 elements, each of type PrisonerRecordPrisonerRecord Prisoner[100];
Arrays of Structures
//Load data into arrayi =0;while (fin >>Prisoner[i].lastName >>
Prisoner[i].firstName >>Prisoner[i].Occupation >> Prisoner[i].MaritalStatus >>Prisoner[i].age >> Prisoner[i].BirthPlace) {
i++;}
DEMO1 CHRIS
Another example of Arrays of Structures
struct Payroll {int id;char name[15];double payrate;
};
// an array of 3 records of type PayrollPayroll employee[3];
Consider the structure below
Arrays of Structures
// load array -- there are other ways to load the array
Payroll employee[3] = { {11, “Bill”, 7.25}, {12, “Paul”, 6.50}, {13, “Maria”, 9.00} };
// display array
for(i = 0; i < 3; i++) {cout << ‘\n’ << employee[i].id << setw(20) << employee[i].name << setw(20) << employee[i].payrate;
}
Arrays of Structures and functions
// prototypesstruct Payroll {
int id;char name[15];double payrate;
};
void loadarray(Payroll staff[ ], int nItems);
void showarray(Payroll staff[ ], int nItems);
int main(){ //declare array of 3 records of type Payroll and initialize the first
record
Payroll employee[3];
loadarray(employee,3); // callsshowarray(employee,3);
cout << endl;return 0;}
Arrays of Structures
// load array - data typically entered via file inputvoid loadarray(Payroll staff[ ], int nItems) {
int i; for(i = 0; i < nItems; i++) {
cout << "Enter the ID, name, and pay rate: "; cin >> staff[i].id >> staff[i].name >>
staff[i].payrate; cout << endl; }}
Arrays of Structures
void showarray(Payroll staff[ ], nItems){ int i;
cout << setiosflags(ios::fixed) << setprecision(2);
for(i = 0; i < 3; i++) { cout << '\n' << setw(5) << staff[i].id
<< setw(13) << staff[i].name << setw(10) << staff[i].payrate;
}}
Nested Structuresstruct ListData {
int id;char name[15];double payrate;
};
struct List {int MaxSize;int nItemsListData Record[100]
};
Called a
Meta Structure
Nested Structures// declaration of an List object //List contains an array of ListData structuresList MyEmployees;
// Initialise list data
MyEmployees.MaxSize = 100;
MyEmployees.nItems = 0;
//Add a record
MyEmployees.Record[0].ID = 123;
strcpy(MyEmployees.Record[0].Name, “SMITH”);
MyEmployees.Record[0].payrate = 10.50;
MyEmployees.nItems++;
Note syntax use of
dots to refer to members.
if a member is a struct, then refer to its members using dot notation
Abstract data types ADT’sExample : A list ADTA list has
max lengthnumber of objects currently storedobjects
Operationscreate list (initialise list members)add objectdisplay listremove objectdestroy list search list for an objectsort listcheck if list is fullcheck if list is emptyetc.
Definition of ADTMost languages have concrete data types- C++ has int , char, float, etc.
The data type determines the range of legitimate values and the operations that can be performed.
The data types provided by the language are called concrete data types.
During the design of a program the need for new data types may arise. for example a record in a database or indeed a whole data base. These objects have ranges of legitimate values and records and databases have legitimate operations.
A formal specification of such objects, defining legitimate ranges and valid operations is an abstract data type. See previous slide. NOTE it must not be specified in C++ form.
Implementation of ADT’s using structs
declare a struct for the datadeclare a struct for the ADT, one member will be the data struct, other typical member is the number of items stored.Initialise/create an ADT object sets the initial members
Create functions that operate on the ADT object.
A List ADT Implementationconst int MAXSIZE = 100;//declare a struct for the datastruct ListData {
int id;char name[15];double payrate;
};//declare a struct for the abstract data typestruct List {
int MaxSize;int nItems;ListData Record[MAXSIZE]
};
//operation prototypesvoid CreateList(List & list);void AddToList(List & list, ListData newdata);void DisplayList(List & list);
A List ADT Implementationint main(void) {
//declare two listsList A;ListData temp; // a temporary variable to add records
CreateList(A); //constructs lists by setting up size to MAXSIZE// and nItems to zero
cout << Enter employee ID, followed by Name and then rate of pay : “;cin >> temp.ID >> temp.name >> temp.payrate;AddToList(A,temp);
DisplayList(A);
return 0;}
operation definitions
//operation definitions for list “construction”void CreateList(List & list){
list.MaxSize = MAXSIZE;list.nItems = 0;
}
operation definitions
//Notice how array subscript is a member of struct i.e list.nItems is used to refer
//to next free element in array.void AddToList(List & list, ListData newdata) {
list.Record[list.nItems].id = newdata.id;list.Record[list.nItems].payrate = newdata.payrate;strcpy(list.Record[list.nItems].name,newdata.name);
//now increment nItems memberlist.nItems++;
}
operation definitions
void DisplayList(List & list){int i;
cout << "There are " << list.nItems << " Employees in the list" << endl;for (i=0;i<list.nItems; i++) {
cout << list.Record[i].id <<" "<< list.Record[i].name <<" "<< list.Record[i].payrate << endl;}
}
DEMO2
Things to come - binding data to functions that use the data.
Functions are loosely associated with structure.It would be nice if the data and operations were bound together.We can! but C++ only, not CAdd function prototypes to struct declaration.Even more tight connection between data and operations via classes.