struct
is just another word for "record"
A data table can be stored as an array of structs.
Shopping List | ||
---|---|---|
Apples | 2 | kg |
Lemonade | 4 | l |
Bread | 1 | kg |
Example: Calculate the centroid of a triangle.
def centroid(x_A, y_A, x_B, y_B, x_C, y_C):
x_G = 1 / 3 * (x_A + x_B + x_C)
y_G = 1 / 3 * (y_A + y_B + y_C)
return x_G, y_G
Structs (or classes) are required for returning more than one value in C++.
struct struct_name {
type member1;
type member2;
/* declare as many members as desired */
};
struct Date {
int year;
int month;
int day;
};
Date d = { 2021, 12, 10 };
Date d = { .year=2021, .month=12, .day=10 };
struct Point {
float x;
float y;
};
Point p = {1.5, 3.0};
struct Point {
float x;
float y;
};
int main() {
Point p1 = { .x=1.5 , .y=3.0 };
Point p2 = p1; // copy assignment
p2.x = -5; // does not affect `p1`
return 0;
}
#include <iomanip>
#include <iostream>
using std::cout, std::fixed, std::setprecision;
struct Point {
float x;
float y;
};
void print_point(Point p) {
cout << fixed << setprecision(2) << "P(" << p.x << "/" << p.y << ")\n";
p.x = 0; // does not affect p in main
}
int main() {
Point p = { .x=1.5 , .y=3.0 };
print_point(p); // pass by value
return 0;
}
struct Point {
float x;
float y;
};
Point centroid(Point A, Point B, Point C) {
float x_G = 1.0 / 3.0 * (A.x + B.x + C.x);
float y_G = 1.0 / 3.0 * (A.y + B.y + C.y);
Point G = {x_G, y_G};
return G;
}
int main() {
Point A = {1.5, 3.0}, B = {12.0, 3.0}, C = {4.5, 9.0};
Point G = centroid(A, B, C); // pass by value
return 0;
}
#include <iostream>
typedef struct {
int id;
char name[25];
unsigned int grades[8];
} Student;
Student read_student(int id) {
// get data from eg. a database
Student s = { id, "Pat Kaling", { 1, 1, 2, 1, 3, 2, 1, 1 } };
return s;
}
int main() {
Student s = read_student(123);
std::cout << s.name << " has a " << s.grades[3] << " in English.";
return 0;
}
struct Date
that holds
int year
,
int month
and int day
.print_date(Date d)
that uses
printf
to print a given date to standard output. The date
must be printed in
ISO 8601
format (YYYY-MM-DD), followed by a newline.Date
in main
and call
print_date
to print today's date.#include <cstdio>
struct Date {
int year;
int month;
int day;
};
void print_date(Date d) {
printf("%04d-%02d-%02d\n", d.year, d.month, d.day);
}
int main() {
Date today = {2021, 12, 9};
print_date(today);
return 0;
}