INTRO TO STRUCTS IN C++
A LECTURE FOR THE C++ COURSE
Each slide may have its own narration in an audio file. �For the explanation of any slide, click on the audio icon to start the narration.
The Professor‘s C++Course by Linda W. Friedman is licensed under a �Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
WHAT IS A STRUCTURE? A RECORD
RECURSION
2
RECORDS
RECURSION
3
|
|
|
|
|
|
|
|
|
|
|
|
| Telephone Numbers | |||
|
|
| Name | Office |
|
|
|
|
| Phone | Phone | |||||
Job Title | Empl ID | Rate | Last | Firs | MI | Bldg | Rm | Project Codes | Area | Local | Area | Local | ||||
ANALYST | 123456789 | 15.93 | Mudd | Joe | H | CSC | 403 | 18 | 40 | 41 | 50 | 53 | 202 | 1234567 | 301 | 1234567 |
The record is a simple yet fundamental type of data structure. A record generally contains an identifying field (key), e.g., EMPLOYEE, a data structure of type record:
Where do we see
STRUCTS IN C++
RECURSION
4
General syntax:
struct structName {
--list of members--
};
EXAMPLES
struct point {
double x;
double y;
};
point p1, p2, p3;
struct point {
double x;
double y;
} p1, p2, p3;
RECURSION
5
Also like this:
struct {
double x;
double y;
} p1, p2, p3;
EXAMPLES
struct point {
double x;
double y;
};
struct rectangle {
point upperLeftCorner;
point lowerRightCorner;
};
struct circle {
point center;
double radius;
};
RECURSION
6
Also these
USING STRUCTS
One way to declare and initialize:
point p5 = {1.0, -8.3};
To access individual members, use the dot operator:
p1.x = 12.45;
p1.y = 34.56;
p2.x = 23.4 / p1.x;
p2.y = 0.98 * p1.y;
RECURSION
7
SMALL EXAMPLE
//structs.cpp
/*illustration of use of structs for organizing data into records*/
#include <iomanip>
#include <fstream>
using namespace std;
ifstream infile ("d:in.dat");
ofstream outfile ("d:out.txt");
struct record { //struct definition
int num1;
int num2;
};
int main(){
record rec; //declaring struct variable rec
float avg;
if (!infile) //testing files
cerr << "Error: could not open input file\n";
else if (!outfile)
cerr << "Error: could not open output file\n";
//printing headings
outfile << setw(18) << "Number 1" � << setw(15)<< "Number 2 "
<< setw(15)<< "Average\n\n";
while (infile >> rec.num1 >> rec.num2){
avg = (rec.num1 + rec.num2) /2.0;
outfile << setiosflags(ios::showpoint | ios::fixed)
<< setprecision(2) << setw(15) <<rec.num1
<< setw(15) << rec.num2
<< setw(15) << avg << endl;
}
return 0;
}
RECURSION
8
INPUT / OUTPUT
RECURSION
9
WHERE TO USE STRUCTS?
What sort of programs are good candidates for using structs?
RECURSION
10
REVIEW
RECURSION
11
What did we learn in this lecture? Plenty. Some terms to jog your memory: