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

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

1 Techniques of Programming CSCI 131 Lecture 24 Structs.
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 10: Records ( structs )
Dale/Weems/Headington
Chapter 10.
Chapter 11: Records (structs)
1 Lecture 24 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 11: Records (structs)
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Lecture 25 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter 8 Arrays and Strings
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Basic Elements of C++ Chapter 2.
EGR 2261 Unit 10 Records (structs)
1 Structured Types, Data Abstraction and Classes.
Chapter 10: Records (structs)
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Chapter 10 Simple Data Types: Built-In and User- Defined.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 11: Records ( struct s)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Chapter 10: Records (structs)
Chapter 10: Records (structs)
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
Cosc237/structures1 Structures aggregate data types record - single variable name for the whole collection composed of several variables - fields,BUT,
1 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Chapter 10 Simple Data Types: Built-In and User- Defined.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
Chapter 10 Simple Data Types: Built-In and User-Defined.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
1 Data Structures and Algorithms Week 3 Data Abstraction: Part II Structured Types, and Classes.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 12-2 Arrays Dale/Weems. 2 Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information n.
1 Structural Types, Data Abstractions and Classes.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 11: Records ( struct s)
1 Chapter 9 Scope, Lifetime, and More on Functions.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
1 Chapter 10 & 11 enum & Structured Types Dale/Weems.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
1 Structured Types, Data Abstraction and Classes.
Chapter 10 Simple Data Types: Built-In and User-Defined
Chapter 12 Classes and Abstraction
What Actions Do We Have Part 1
Dale/Weems/Headington
Chapter 10 Simple Data Types: Built-In and User-Defined
Basic Elements of C++ Chapter 2.
Chapter 10: Records (structs)
What Actions Do We Have Part 1
Structures Structured Data types Data abstraction structs ---
Presentation transcript:

Structures (aka records, structs) Textbook Chapter 11 sections:

2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

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

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?

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

6 oneAnimal 5000.id name “giant panda”.genus “Ailuropoda”.species “melanoluka”.country “China”.age 18.weight health Good

7 anotherAnimal 6000.id name “llama”.genus “Lama”.species “peruana”.country “Peru”.age 7.weight health “Excellent”

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

9 Struct Type Declaration struct AnimalType// declares a struct data type {// does not allocate any memory long id ; string name ; string genus ; string species ; struct members string country ; int age ; float weight ; string health ; } ; // NOTE THE SEMICOLON 9

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!

11 Struct Variable Declaration int main() { // declare variables of AnimalType AnimalType oneAnimal ; AnimalType anotherAnimal ; … } 11

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.

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

14 Valid operations on a struct member depend only on its type oneAnimal.age = 18; oneAnimal.id = ; cin >> oneAnimal.weight; getline ( cin, oneAnimal.species ); oneAnimal.name = “giant panda”; oneAnimal.genus[ 0 ] = toupper (oneAnimal.genus[ 0 ] ) ; oneAnimal.age++;

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

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

17 Assignment struct copy or assignment anotherAnimal = oneAnimal; Copies each member from oneAnimal struct to anotherAnimal struct

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

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

20 Passing struct by Reference Same as other reference parameters –use & to identify in parameter list

21 void IncrementAge (AnimalType& thisAnimal ) // Adds 1 to age // Precondition: thisAnimal.age is assigned // Postcondition: thisAnimal.age == + 1 { thisAnimal.age++ ; } Passing a struct by Reference

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)

23 struct as a Return Value You can also return an entire struct variable from a function.

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

25 Input/Output No aggregate input/output operations on a struct variable cout<<oneAnimal; //does NOT work cin>>anotherAnimal; //does NOT work!!!

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;

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

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…

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

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

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

32 struct DateType {int month ; // Assume int day ;// Assume int year ; // Assume }; struct StatisticsType {floatfailRate ; DateTypelastServiced ; // DateType is a struct type intdownDays ; } ; struct MachineRec {int idNumber ; string description ; StatisticsType history ; // StatisticsType is a struct type DateType purchaseDate ; float cost ; } ; MachineRec machine ; 32

33 struct type variable machine 7000.idNumber.description. history.purchaseDate.cost.month.day.year 5719 “DRILLING…” failrate.lastServiced.downdays month.day.year machine.history.lastServiced.year has value 1999

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 };

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?

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

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

38 Include File Example // Functions for the sales by quarter program #include // system runtime files #include using namespace std; #include "salesPerson.h" // sales person header file

39 System Includes vs. User Includes Note how system files are included: #include // using angle brackets Note how your header files are included: using namespace std; #include "salesPerson.h" Put inside double quotes After the “using” statement

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

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

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

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

44 Output Format Annual Sales Report ID QT1 QT2 QT3 QT4 Total _______________________________________________________________ Total Max Sale by SalesPerson: ID = 57373, Amount = $ Max Sale by Quarter: Quarter = 3, Amount = $ 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)

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

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.

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

48