CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type Prof. amr Goneid, AUC 1
The Struct Data Type Prof. amr Goneid, AUC 2
The Struct Data Type What are Structs ? Definition & Declaration Accessing Members of a Struct Initializing a Struct Variable Compound Structs Structs as Operands & Arguments Pointers to Structs Prof. amr Goneid, AUC 3
1. What are structs? Structs are linear Data Structures. Unlike the array, components ( members ) can be of different types . string Member 1 int Member 2 One struct longint char Member n int Prof. amr Goneid, AUC 4
2. Definition & Declaration (a) Define a struct type: struct <struct type> { <type 1> <member 1>; <type 2> <member 2>; …… <type n> <member n>; }; (b) Declare variables of that type: Required ; <struct type> <var1> <var2> .. ; Prof. amr Goneid, AUC 5
Example // Definition of struct employee struct employee { string id; string name; char gender; int numDepend; money rate; money totWages; }; employee engineer , assistant; Prof. amr Goneid, AUC 6
3. 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: s.m Can use C++ operators and operations on struct members Prof. amr Goneid, AUC 7
Accessing Members of a struct engineer.id = “1234”; engineer.name = “Heba Ahmed”; engineer.gender = ‘F’; engineer.numDepend = 0; engineer.rate = 6.00; engineer.totWages += engineer.rate * 40.0; Prof. amr Goneid, AUC 8
What you can do with a whole struct Assign a struct to another struct with exactly the same structure (copy) Pass a struct to a function by value or by reference Return a struct as a function type Prof. amr Goneid, AUC 9
BUT you cannot Input or output a whole struct Do arithmetic with whole structs Compare two whole structs The above operations can only be done on individual members of structs Prof. amr Goneid, AUC 10
4. Initializing a Struct Variable Members can be initialized at the time a structure variable is created using a constructor A constructor is a special function that can be a member of a structure It is normally written inside the struct declaration Its purpose is to initialize the structure’s data members Prof. amr Goneid, AUC 11
Initializing using a Constructor Unlike most functions, a constructor is not called; instead, it is automatically invoked when a structure variable is created The constructor name must be the same as the structure Type name The constructor must have no return type Prof. amr Goneid, AUC 12
Initializing using a Constructor Example: struct Dimensions { int length, width, height; // Constructor Dimensions(int L, int W, int H) {length = L; width = W; height = H;} }; Usage: Dimensions box(12, 6, 3); Prof. amr Goneid, AUC 13
5. Compound structs: Structs with Array Members // Arrays can be fields of structs, e.g. struct studentRecord { string name; string id; float grade [10]; float GPA; }; studentRecord student; student.grade[3] = 3.6; cin >> student.name; for( i = 0; i < 10; i++) cin >> student.grade[i]; Prof. amr Goneid, AUC 14
Structs with Struct Members // A member of a struct may itself be a struct,e.g. struct nameType { cin >> person.address; string first; cin >> person.phone; string middle; cin >> person.name.first; string last; cin >> person.name.last; }; struct personInfo { nameType name; string address; string phone; }; personInfo person; Prof. amr Goneid, AUC 15
Structs with Struct Members struct point{ p.x,p.y double x, y; }; point P; struct line{ L.p1.x,L.p1.y L.p2.x,L.p2.y point p1, p2; }; line L; struct triangle{ T.p2.x,T.p2.y T.p3.x,T.p3.y point p1, p2, p3; }; triangle T; T.p1.x,T.p1.y Prof. amr Goneid, AUC 16
Arrays of Structs // A struct may be an element of an // array,e.g . personInfo staff [100]; cout << staff [i].address; cout << staff [i].name.first; for( i = 0; i < N; i++) { cout << staff [i].phone; cout << staff [i].name.family; } Prof. amr Goneid, AUC 17
6. Structs as Operands and Arguments Arithmetic and other operations can be done struct members Process entire struct using programmer defined functions Often better to pass an entire structure rather than individual elements struct copies: person = staff [6]; Prof. amr Goneid, AUC 18
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 Prof. amr Goneid, AUC 19
Example(1): Grading Program // FILE: StudentStat.h struct studentStat { string name; int scores[3]; float average; char grade; }; Prof. amr Goneid, AUC 20
PrintStats.cpp // File: printStats.cpp // Prints the exam statistics // Pre: The members of the struct variable // student are assigned values. // Post: Each member of student is displayed. void printStats(const studentStat student) { cout << "Exam scores for " << student. name << ": " Prof. amr Goneid, AUC 21
PrintStats.cpp cout << student.scores[0] << ' ' << student.scores[1]<< ' ' << student.scores[2] << endl; cout << "Average score: " << student.average << endl; cout << "Letter grade : " << student.grade << endl; } Prof. amr Goneid, AUC 22
Example(2): ReadEmp.cpp // File: ReadEmp.cpp // Reads one employee record into oneemployee #include <string> #include <iostream> // Pre: None // Post: Data are read into struct oneEmployee void readEmployee(employee& oneEmployee) { cout << "Enter a name terminated by # : "; Prof. amr Goneid, AUC 23
ReadEmp.cpp getline(cin, oneEmployee.name, '#'); cout << "Enter an id number: "; cin >> oneEmployee.id; cout << "Enter gender (F or M): "; cin >> oneEmployee.gender; cout << "Enter number of dependents: "; cin >> oneEmployee.numDepend; cout << "Enter hourly rate: "; cin >> oneEmployee.rate; } Prof. amr Goneid, AUC 24
7. Pointers to Structs struct electric { string current; int volts; }; electric *p, *q; //p and q are pointers to a struct of type electric Prof. amr Goneid, AUC 25
Pointers to Structs p = new electric; Allocates storage for struct of type electric and places address into pointer p current volts p ? ? Use operator ( . ) to access struct members. Prof. amr Goneid, AUC 26
Assignments *p.current = “AC”; *p.volts = 220; current volts p AC 220 Statements above can also be written as p ->current = “AC”; p ->volts = 220; Prof. amr Goneid, AUC 27
Struct Member Access via Pointers Form: p -> <member> Example: p -> volts Example: cout << p->current << p-volts << endl; Output AC220 Prof. amr Goneid, AUC 28
Copy Dynamic Structs q = new electric; Allocates storage for struct of type electric and places address into pointer q Copy contents of p struct to q struct *q = *p; q ->current q ->volts q AC 220 Prof. amr Goneid, AUC 29
The Linked List Structure Structs and pointers can be used to arrange dynamically allocated structures into a new structure called a linked list Example: Consider a very long number represented as a string, e.g. π string Long_pi = “ 3.1415926535897932384626433832795028 8419716939937510……….”; Prof. amr Goneid, AUC 30
The Simple Linked List We can build a sequence of nodes linked by pointers: . 3 1 Last NULL head First next cursor First node pointed to by head contains the first digit ‘3’ and a next pointer to next node containing ‘.’ and so on. Last node’s next is NULL. A cursor points to the current node. It can advance in one way only to next node, e.g. to traverse whole list. Prof. amr Goneid, AUC 31
The Node Structure struct node // specify node structure { char d; // digit or ‘.’ node *next; // pointer to next node }; node *head, *cursor , *p; // pointers to nodes d next Prof. amr Goneid, AUC 32
Code segment // Create first node p = new node; p->d = Long_pi[0]; p-> next = NULL; head = cursor = p; //Create rest of nodes for (i = 1; i < Long_pi.length(); i++){ p = new node; p->d = Long_pi[i]; p->next = NULL; cursor->next = p; cursor = cursor->next; } Prof. amr Goneid, AUC 33
Recommend
More recommend