Upload
others
View
10
Download
0
Embed Size (px)
Citation preview
Prof. amr Goneid, AUC 1
CSCE 110PROGRAMMING FUNDAMENTALS
WITH C++
Prof. Amr GoneidAUC
Part 11. The Struct Data Type
Prof. amr Goneid, AUC 2
The Struct Data Type
Prof. amr Goneid, AUC 3
The Struct Data Type
What are Structs ?Definition & Declaration Accessing Members of a Struct Initializing a Struct VariableCompound Structs Structs as Operands & Arguments Pointers to Structs
Prof. amr Goneid, AUC 4
1. What are structs?
Structs are linear Data Structures.Unlike the array, components
(members) can be of different types.
stringint
longint
int
Member 1Member 2
Member n
One structchar
Prof. amr Goneid, AUC 5
(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:
<struct type> <var1> <var2> .. ;
2. Definition & Declaration
Required ;
Prof. amr Goneid, AUC 6
Example
// Definition of struct employeestruct employee{
string id;string name;char gender;int numDepend;money rate;money totWages;
};employee engineer , assistant;
Prof. amr Goneid, AUC 7
3. Accessing Members of a structMembers 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 8
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 9
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 10
BUT you cannot
Input or output a whole structDo arithmetic with whole structsCompare two whole structsThe above operations can only be
done on individual members of structs
Prof. amr Goneid, AUC 11
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 structdeclaration
Its purpose is to initialize the structure’s data members
Prof. amr Goneid, AUC 12
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 13
Initializing using a ConstructorExample: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 14
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 15
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 16
Structs with Struct Members
struct point{ double x, y;};
point P;struct line{
point p1, p2;};
line L;struct triangle{
point p1, p2, p3;};
triangle T;
p.x,p.y
L.p1.x,L.p1.y L.p2.x,L.p2.y
T.p1.x,T.p1.y
T.p2.x,T.p2.y T.p3.x,T.p3.y
Prof. amr Goneid, AUC 17
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 18
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 19
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 variableGroup all related student items together Pass struct by const reference if you do
not want changes made
Prof. amr Goneid, AUC 20
Example(1): Grading Program
// FILE: StudentStat.h
struct studentStat{
string name;int scores[3];float average;char grade;
};
Prof. amr Goneid, AUC 21
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 22
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 23
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 oneEmployeevoid readEmployee(employee& oneEmployee) {
cout << "Enter a name terminated by # : ";
Prof. amr Goneid, AUC 24
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 25
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 26
Pointers to Structs
p = new electric; Allocates storage for struct of type electric
and places address into pointer p
Use operator ( . ) to access struct members.
?
current voltsp?
Prof. amr Goneid, AUC 27
Assignments
*p.current = “AC”;*p.volts = 220;
Statements above can also be written asp ->current = “AC”;p ->volts = 220;
AC
current voltsp
220
Prof. amr Goneid, AUC 28
Struct Member Access via Pointers Form: p -> <member> Example: p -> volts
Example:cout << p->current << p-volts << endl;Output
AC220
Prof. amr Goneid, AUC 29
Copy Dynamic Structsq = 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;
AC
q ->current q ->voltsq
220
Prof. amr Goneid, AUC 30
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.14159265358979323846264338327950288419716939937510……….”;
Prof. amr Goneid, AUC 31
The Simple Linked List We can build a sequence of nodes linked by
pointers:
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.
3 1head NULL
cursor
.
nextFirst Last
Prof. amr Goneid, AUC 32
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 33
Code segment// Create first nodep = new node;p->d = Long_pi[0]; p-> next = NULL;head = cursor = p;
//Create rest of nodesfor (i = 1; i < Long_pi.length(); i++){
p = new node; p->d = Long_pi[i]; p->next = NULL;cursor->next = p;cursor = cursor->next;
}