All lessons
LESSON 26/53Bigger Programs
Structs: Your Own Type
GOALGroup several related values into one thing.

Keeping a student's name, grade and average in three separate variables gets messy fast. A struct puts them together under one name.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int grade;
double average;
};
int main() {
Student s;
s.name = "Bat";
s.grade = 8;
s.average = 92.5;
cout << s.name << " (grade " << s.grade << ") "
<< s.average << endl;
Student best = s; // бүх талбар нь хамт хуулагдана / every field is copied
cout << best.name << endl;
return 0;
}> what you see
Bat (grade 8) 92.5 Bat
//LINE BY LINE
Watch it run
struct Student declares a SHAPE — no variable exists yet.
Why bother
Without a struct — this falls apart quickly:
string name1, name2, name3;
int grade1, grade2, grade3;
double avg1, avg2, avg3; // 30 сурагч болбол яах вэ?With a struct:
struct Student {
string name;
int grade;
double average;
};
Student cls[30]; // 30 сурагч, нэг л мөрAn array of structs
The most common use: store many records and walk through them with a loop.
Student cls[3];
cls[0].name = "Bat"; cls[0].average = 92.5;
cls[1].name = "Saraa"; cls[1].average = 88.0;
cls[2].name = "Tuya"; cls[2].average = 95.5;
// Хамгийн өндөр дунджтайг олох
int best = 0;
for (int i = 1; i < 3; i++) {
if (cls[i].average > cls[best].average) best = i;
}
cout << cls[best].name; // Tuya> what you see
Tuya
Passing a struct to a function
A struct can be large, so pass it by const & to avoid copying it.
void show(const Student& s) {
cout << s.name << ": " << s.average << endl;
}
show(cls[0]);