MIS 120 Structures
The Problem Recall that elements of arrays must all be of the SAME type. In some cases, we want to group elements of DIFFERENT types. scores : 85 79 92 57 68 80 . . . employee R. Jones 123 Elm 6/12/55 $14.75
Solving with Parallel Arrays We learned in Chapter 11 that one way to solve this problem is with parallel arrays. While parallel arrays will solve the problem, they are inefficient and put a heavy burden on the developer and QA. 1 2 3 4 5 Student Name Jeff Joey Susan Joanne Dhale Becky Exam 1 Grade 104 78 92 84 52 87 Exam 2 Grade 128 91 88 110 40 115
Records RECORDS are used to group related components of different types Components of the record are called fields In C++ record called a struct (structure) fields called members
Solving with a Struct C++ struct structured data type fixed number of components elements accessed by name, not by index components may be of different types struct partStruct { string descrip, partNum; float unitPrice; int qty; };
Declaring Struct Variables Given Declare Use struct partStruct { string descrip, partNum; float unitPrice; int qty; }; partStruct myPart; myPart.descrip = “Tire”; myPart.unitPrice = 55.25; cout << myPart.descrip << “are $” << myPart.unitPrice << “each.”;
Use within Functions A struct variable can be passed as a parameter Can be passed by value or by reference. A function can return a value of the type struct
Some Limitations No aggregate Input/Output operations Data must be read one member at a time Contents must be written one member at a time. Compares must be done one member at a time if(student.firstName == newStudent.firstName && student.lastName == newStudent.lastName) ...
The True Power of Structs! You can declare an Array of Structs! First declare a struct (such as partStruct) Then specify an array of that type You can then access any member within the array partStruct partList [50]; for (x = 0; x <50; x++) cout << partList[x].descrip;
Questions?