cpp / beginner
Snippet
Structures to Group Data
Structures (struct) group related data items together under one name. Unlike arrays which hold many items of the same type, structs can hold different data types. You can add member functions to structs to give them behavior. Structs are the foundation for creating custom data types.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>#include <string>struct Student {std::string name;int age;float gpa;void printInfo() {std::cout << name << ", Age: " << age << ", GPA: " << gpa << std::endl;}bool hasHonors() {return gpa >= 3.5f;}};int main() {Student student1;student1.name = "Anna Schmidt";student1.age = 20;student1.gpa = 3.8f;Student student2 = {"Ben Mueller", 22, 3.2f};student1.printInfo();student2.printInfo();std::cout << student1.name << " has honors: "<< (student1.hasHonors() ? "Yes" : "No") << std::endl;return 0;}
Breakdown
1
struct Student {
Begins defining a structure named Student that groups multiple pieces of data together
2
std::string name;
Member variable storing the student's name as a string
3
int age;
Member variable storing the student's age as an integer
4
void printInfo()
Member function that prints all the student's information to the console
5
Student student2 = {"Ben Mueller", 22, 3.2f};
Initializes a Student struct with values in the order they were declared in the struct