A structure in C++ is a user-defined composite data type that groups variables of different types under a single name.
Defining and Using a Structure
#include <iostream>
#include <string>
using namespace std;
struct PersonData {
string fullName;
int yearsOld;
int examScore;
} personThree; // Variable declared with the structure
int main() {
// Method 1: Declare and initialize separately
PersonData personOne;
personOne.fullName = "Alex Johnson";
personOne.yearsOld = 22;
personOne.examScore = 95;
cout << "Name: " << personOne.fullName << " Age: " << personOne.yearsOld << " Score: " << personOne.examScore << endl;
// Method 2: Initialize during declaration
PersonData personTwo = {"Jamie Smith", 21, 88};
cout << "Name: " << personTwo.fullName << " Age: " << personTwo.yearsOld << " Score: " << personTwo.examScore << endl;
// Method 3: Using the variable declared with the structure
personThree.fullName = "Taylor Brown";
personThree.yearsOld = 23;
personThree.examScore = 72;
cout << "Name: " << personThree.fullName << " Age: " << personThree.yearsOld << " Score: " << personThree.examScore << endl;
return 0;
}
Array of Structures
#include <iostream>
#include <string>
using namespace std;
struct Employee {
string employeeName;
int employeeId;
double salary;
};
int main() {
Employee staff[3] = {
{"Robert Chen", 101, 55000.0},
{"Lisa Wang", 102, 62000.0},
{"David Kim", 103, 48000.0}
};
staff[1].employeeName = "Sarah Jones"; // Modifying an element
for (int i = 0; i < 3; ++i) {
cout << "ID: " << staff[i].employeeId
<< " Name: " << staff[i].employeeName
<< " Salary: $" << staff[i].salary << endl;
}
return 0;
}
Pointers to Structures
#include <iostream>
#include <string>
using namespace std;
struct Product {
string productName;
float price;
int stock;
};
int main() {
Product item = {"Wireless Mouse", 29.99, 150};
Product* itemPtr = &item;
cout << "Product: " << itemPtr->productName
<< " Price: $" << itemPtr->price
<< " Stock: " << itemPtr->stock << endl;
return 0;
}
Nested Structures
#include <iostream>
#include <string>
using namespace std;
struct Date {
int day;
int month;
int year;
};
struct Event {
string eventTitle;
string location;
Date eventDate; // Nested structure
};
int main() {
Event conference;
conference.eventTitle = "Tech Summit";
conference.location = "Convention Center";
conference.eventDate.day = 15;
conference.eventDate.month = 6;
conference.eventDate.year = 2024;
cout << "Event: " << conference.eventTitle
<< " at " << conference.location
<< " on " << conference.eventDate.month
<< "/" << conference.eventDate.day
<< "/" << conference.eventDate.year << endl;
return 0;
}
Structures as Funciton Parameters
#include <iostream>
#include <string>
using namespace std;
struct Measurement {
double length;
double width;
};
// Pass by value
void displayMeasureByValue(Measurement m) {
m.length = 0.0; // Change does not affect original
cout << "In function (value): Length=" << m.length
<< " Width=" << m.width << endl;
}
// Pass by address
void displayMeasureByPointer(Measurement* mPtr) {
mPtr->width = 99.9; // Change affects original
cout << "In function (pointer): Length=" << mPtr->length
<< " Width=" << mPtr->width << endl;
}
int main() {
Measurement room = {10.5, 8.2};
Measurement box = {3.0, 2.5};
displayMeasureByValue(room);
displayMeasureByPointer(&box);
cout << "Main - room: " << room.length << ", " << room.width << endl;
cout << "Main - box: " << box.length << ", " << box.width << endl;
return 0;
}
Using const with Structure Pointers
#include <iostream>
#include <string>
using namespace std;
struct Account {
string username;
int loginCount;
};
void printAccountData(const Account* accPtr) {
// accPtr->loginCount = 0; // Error: cannot modify const data
cout << "User: " << accPtr->username
<< " Logins: " << accPtr->loginCount << endl;
}
int main() {
Account userAcc = {"dev_user", 42};
printAccountData(&userAcc);
cout << "Original login count unchanged: " << userAcc.loginCount << endl;
return 0;
}
Practical Example: Classroom Management
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Pupil {
string pupilName;
int testResult;
};
struct Instructor {
string instructorName;
Pupil classList[5];
};
void setupClassroom(Instructor staff[], int numInstructors) {
string idLetters = "ABCDE";
for (int i = 0; i < numInstructors; ++i) {
staff[i].instructorName = "Prof_" + string(1, idLetters[i]);
for (int j = 0; j < 5; ++j) {
staff[i].classList[j].pupilName = "Student_" + string(1, idLetters[j]);
staff[i].classList[j].testResult = (rand() % 61) + 40;
}
}
}
void showClassData(Instructor staff[], int numInstructors) {
for (int i = 0; i < numInstructors; ++i) {
cout << "\nInstructor: " << staff[i].instructorName << endl;
for (int j = 0; j < 5; ++j) {
cout << " Pupil: " << staff[i].classList[j].pupilName
<< " Score: " << staff[i].classList[j].testResult << endl;
}
}
}
int main() {
srand(time(nullptr));
Instructor faculty[3];
int facultyCount = sizeof(faculty) / sizeof(faculty[0]);
setupClassroom(faculty, facultyCount);
showClassData(faculty, facultyCount);
return 0;
}
Practcial Example: Sorting an Array of Structuers
#include <iostream>
#include <string>
using namespace std;
struct GameCharacter {
string charName;
int healthPoints;
string characterClass;
};
void sortCharacters(GameCharacter roster[], int count) {
for (int i = 0; i < count - 1; ++i) {
for (int j = 0; j < count - i - 1; ++j) {
if (roster[j].healthPoints > roster[j + 1].healthPoints) {
GameCharacter swapTemp = roster[j];
roster[j] = roster[j + 1];
roster[j + 1] = swapTemp;
}
}
}
}
void displayRoster(GameCharacter roster[], int count) {
for (int i = 0; i < count; ++i) {
cout << "Name: " << roster[i].charName
<< " HP: " << roster[i].healthPoints
<< " Class: " << roster[i].characterClass << endl;
}
}
int main() {
GameCharacter party[5] = {
{"Arthas", 85, "Paladin"},
{"Sylvanas", 70, "Ranger"},
{"Thrall", 92, "Shaman"},
{"Jaina", 68, "Mage"},
{"Illidan", 95, "Demon Hunter"}
};
int partySize = sizeof(party) / sizeof(party[0]);
sortCharacters(party, partySize);
displayRoster(party, partySize);
return 0;
}