structures (aka records, structs) textbook chapter 11 sections: 11.1 11.2 1

48
Structures (aka records, structs) Textbook Chapter 11 sections: • 11.1 • 11.2 1

Upload: morris-barker

Post on 20-Jan-2016

235 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

Structures (aka records, structs)

Textbook Chapter 11 sections:

• 11.1

• 11.2

1

Page 2: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

2

C++ Data TypesC++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Page 3: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

3

C++ Data Types

• There are simple data types that hold only one value

• There are structured data types that hold multiple values

• The array was the first example of a structured data type that can hold multiple values

• The structure is the second example

Page 4: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

4

C++ Structs

• often we have related information of various types that we’d like to store together for convenient access under the same identifier…

• Why not use simple data types or arrays?

Page 5: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

5

The struct Data Type

• struct used to store a collection of related data items

• Individual components of the struct are called its members

• Each member can be a different type of data

Page 6: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

6

oneAnimal

5000

.id 2037581

.name “giant panda”

.genus “Ailuropoda”

.species “melanoluka”

.country “China”

.age 18

.weight 234.6

.health Good

Page 7: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

7

anotherAnimal

6000

.id 5281003

.name “llama”

.genus “Lama”

.species “peruana”

.country “Peru”

.age 7

.weight 278.5

.health “Excellent”

Page 8: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

8

Using the struct Data Type

• Three steps to use– declaration of struct type– use of struct type to define a new variable– access of members of the struct variable(s)

• Typically declare struct type globally

Page 9: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

9

Struct Type Declaration

struct AnimalType // declares a struct data type{ // does not allocate any

memorylong id ;string name ;string genus ;string species ; struct members string country ; int age ; float weight ; string health ;

} ; // NOTE THE SEMICOLON 9

Page 10: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

10

struct type Declaration

The struct declaration creates a type and names the members of that type.

It does not allocate memory for any variables of that type!

You still need to declare your struct variables to use them!

Page 11: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

11

Struct Variable Declaration

int main(){// declare variables of AnimalTypeAnimalType oneAnimal ;AnimalType anotherAnimal ;…}

11

Page 12: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

12

More about struct declarations

If the struct type declaration precedes all functions it will be visible throughout the rest of the file. If it is placed within a function, only that function can use it.

It is common to place struct type declarations within a (.h) header file and #include that file (more on this later).

It is possible for members of different struct types to have the same identifiers. Also a non-struct variable may have the same identifier as a structure member.

Page 13: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

13

Accessing struct Members

Dot ( period ) is the member selection operator.

After the struct type declaration, the various members can be used in your program only when they are preceded by a struct variable name and a dot.

EXAMPLES

oneAnimal.weight

anotherAnimal.country

Page 14: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

14

Valid operations on a struct member depend only on its type

oneAnimal.age = 18;

oneAnimal.id = 2037581;

cin >> oneAnimal.weight;

getline ( cin, oneAnimal.species );

oneAnimal.name = “giant panda”;

oneAnimal.genus[ 0 ] = toupper (oneAnimal.genus[ 0 ] ) ;

oneAnimal.age++;

Page 15: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

15

Aggregate Operation

• is an operation on a data structure as a whole, as opposed to an operation on an individual component of the data structure

Page 16: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

16

Aggregate struct Operations

I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED!

Operations valid on an entire struct type variable:

• assignment to another struct variable of same type,

• pass to a function as argument (by value or by reference),

• return as value of a function

Page 17: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

17

Assignment

• struct copy or assignment

anotherAnimal = oneAnimal;

• Copies each member from oneAnimal struct to anotherAnimal struct

Page 18: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

18

Passing as a “By-Value” 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 19: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

19

void WriteOut(AnimalType thisAnimal)

// Prints out values of all members of thisAnimal

// Precondition: all members of thisAnimal are assigned

// Postcondition: all members have been written out{

cout << “ID # “ << thisAnimal.id << thisAnimal.name << endl ;

cout << thisAnimal.genus << thisAnimal.species << endl ;

cout << thisAnimal.country << endl ;

cout << thisAnimal.age << “ years “ << endl ;

cout << thisAnimal.weight << “ lbs. “ << endl ;

cout << “General health : “ ;

WriteWord ( thisAnimal.health ) ;}

19

Page 20: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

20

Passing struct by Reference

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

Page 21: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

21

void IncrementAge (AnimalType& thisAnimal )

// Adds 1 to age// Precondition: thisAnimal.age is assigned // Postcondition: thisAnimal.age == thisAnimal.age@entry + 1

{

thisAnimal.age++ ;

}

Passing a struct by Reference

Page 22: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

22

Passing struct by Reference

• Can also use constant reference to avoid copying large structs but keep function from modifying contents:– precede parameter with reserved word const

void WriteOut(const AnimalType& thisAnimal)

Page 23: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

23

struct as a Return Value

• You can also return an entire struct variable from a function.

Page 24: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

24

Comparison (Relational Operators)

• Compare struct variables member-wise (NOT THE WHOLE STRUCTURE)

• What does it mean for one animal to be greater than another?

• It makes more sense for one animal’s age to be greater than another’s age…

if(oneAnimal.age > anotherAnimal.age)…

Page 25: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

25

Input/Output

• No aggregate input/output operations on a struct variable

cout<<oneAnimal; //does NOT work

cin>>anotherAnimal; //does NOT work!!!

Page 26: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

26

Input/Output

• Data in a struct variable must be read one member at a time

cin>>oneAnimal.id;

• The contents of a struct variable must be written one member at a time

cout<<oneAnimal.age;

Page 27: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

27

Also Note that arrays CANNOT store member components of multiple types, structures can…

Page 28: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

28

Using Functions with Structs

• You can write utility functions to accompany your struct data types– Read struct data from keyboard/file– Write struct data to a specified stream– Etc…

Page 29: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

29

void GetAnimalData (AnimalType newAnimal)

// Obtains all information about an animal from keyboard

// Postcondition: AnimalType members filled{

cout<<“\nPlease Enter the Animal’s ID:”;cin>>newAnimal.id;

//… continue until all data is filled

}29

Page 30: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

30

Hierarchical Structures

The type of a struct member can be another struct type. This is called nested or hierarchical structures.

Hierarchical structures are very useful when there is much detailed information in each record.

FOR EXAMPLE . . .

Page 31: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

31

struct MachineRec

Information about each machine in a shop contains:

an idNumber,

a written description,

the purchase date,

the cost,

and a history (including failure rate, number of days down, and date of last service).

Page 32: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

32

struct DateType

{ int month ; // Assume 1 . . 12

int day ; // Assume 1 . . 31

int year ; // Assume 1900 . . 2050

};

struct StatisticsType

{ float failRate ;

DateType lastServiced ; // DateType is a struct type

int downDays ;

} ;

struct MachineRec

{ int idNumber ;

string description ;

StatisticsType history ; // StatisticsType is a struct type

DateType purchaseDate ;

float cost ;

} ;

MachineRec machine ; 32

Page 33: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

33

struct type variable machine

7000

.idNumber .description . history .purchaseDate .cost

.month .day .year

5719 “DRILLING…” 3 21 1995 8000.0

.failrate .lastServiced .downdays

.02 1 25 1999 4.month .day .year

machine.history.lastServiced.year has value 1999

Page 34: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

34

Arrays IN structs• Two key items are associated with a list:

– Values (elements)– Length of the list

• Define a struct containing both items:const int CAPACITY = 1000;

struct listType

{

int listElem[CAPACITY]; //array containing the list

int listLength; //current length of the list

};

Page 35: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

35

Arrays OF structs

• It is possible to declare an array of structs, after all, once declared your struct type is another recognized data type

• The following line of code declares an array of AnimalType structs.

AnimalType zooAnimals[NUM_ANIMALS];

• How do we access a member of one of these structures?

Page 36: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

36

Organization of Large Programs• Large programs are composed of multiple

source files. Each source file is compiled then linked into an executable program

• So that your struct type definitions can be used in all the source files, they are put in header files (include files)

• The header file is then included in each source file where the struct type is needed using the #include directive

Page 37: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

37

Include Files• The #include statement inserts the named

file in this source code

• It is typically used for type and function definitions needed by the source file

• Structures are the first example of the need for you to use your own include file

• Using include files means that you only define the structure once no matter how many files it is used in

Page 38: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

38

Include File Example

// Functions for the sales by quarter program

#include <iostream> // system runtime files

#include <fstream>

#include <iomanip>

#include <string>

using namespace std;

#include "salesPerson.h" // sales person header file

Page 39: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

39

System Includes vs. User Includes

• Note how system files are included:#include <iostream> // using angle brackets• Note how your header files are included:

using namespace std;

#include "salesPerson.h"

• Put inside double quotes

• After the “using” statement

Page 40: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

40

Summary• Struct: collection of a fixed number of

components

• Components can be of different types

• struct is a reserved word

• No memory is allocated for a struct; memory is allocated for struct variables when declared

• Components of a struct are called members

Page 41: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

41

Summary

• struct components are accessed by name

• Dot (.) operator is called the member access operator

• Members of a struct are accessed using the dot (.) operator

• The only built-in operations on a struct are the assignment and member access

Page 42: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

42

Summary

• Neither arithmetic nor relational operations are allowed on the entire structure

• structures can be passed by value or reference

• A function can return a structure

• A structure can be a member of another structure

Page 43: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

43

Programming Example• A company has six salespeople

• Every month they go on road trips to sell the company’s product

• At the end of each month, the total sales for each salesperson, salesperson’s ID, and the month, are recorded in a file

• At the end of each year, the manager of the company asks for a report

Page 44: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

44

Output Format----------- Annual Sales Report -------------

ID QT1 QT2 QT3 QT4 Total_______________________________________________________________12345 1892.00 0.00 494.00 322.00 2708.0032214 343.00 892.00 9023.00 0.00 10258.0023422 1395.00 1901.00 0.00 0.00 3296.0057373 893.00 892.00 8834.00 0.00 10619.0035864 2882.00 1221.00 0.00 1223.00 5326.0054654 893.00 0.00 392.00 3420.00 4705.00Total 8298.00 4906.00 18743.00 4965.00

Max Sale by SalesPerson: ID = 57373, Amount = $10619.00Max Sale by Quarter: Quarter = 3, Amount = $18743.00

QT1 stands for quarter 1 (months 1 to 3), QT2 for quarter 2 (months 4 to 6), QT3 for quarter 3 (months 7 to 9) and QT4 for quarter 4 (months 10 to 12)

Page 45: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

45

Programming Example

• The salespeople IDs are stored in one file; sales data are stored in another file

• The sales data is in the following form:

salesPersonID month saleAmount

.

.

.

• Sales data are not ordered

Page 46: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

46

Data Design

• Design an appropriate scheme for organizing your input data.

• Once the data is properly organized, you can design algorithms to operate on that data to perform the necessary tasks.

Page 47: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

47

Program Analysis

• There are six people, so an array of 6 components is used

• Because the program requires the company’s total sales for each quarter

– We need an array of four components to store the data

Page 48: Structures (aka records, structs) Textbook Chapter 11 sections: 11.1 11.2 1

48