Organizing Complex Data with C++ Structures
Defining Structures in C++
A struct (short for structure) is a user-defined data type that allows you to combine data items of different types. While arrays are limited to collections of the same type, structs are ideal for representing real-world enttiies, such as a student with a name, an ID, and multiple grades.
Member Access and Basic Operations
To define a structure, use the struct keyword followed by the name of the type and its members. You access these members using the dot (.) operator.
struct Candidate {
std::string fullName;
int scoreA;
int scoreB;
int scoreC;
};
Example 1: Identifying the Top Performer
Consider a scenario where you need to process multiple student records and identify the one with the highest aggregate score. Using a struct allows you to keep the name and individual scores linked together as a single object.
#include <iostream>
#include <string>
struct StudentInfo {
std::string name;
int math;
int history;
int science;
};
int main() {
int count;
if (!(std::cin >> count)) return 0;
StudentInfo current;
StudentInfo best;
int maxTotal = -1;
for (int i = 0; i < count; ++i) {
std::cin >> current.name >> current.math >> current.history >> current.science;
int currentTotal = current.math + current.history + current.science;
if (currentTotal > maxTotal) {
maxTotal = currentTotal;
best = current;
}
}
std::cout << best.name << " " << best.math << " " << best.history << " " << best.science << std::endl;
return 0;
}
Example 2: Comparing Records for Similarity
Structs are also effective when storing data in arrays to perform comparisons between different entries. For instance, the following code finds pairs of students whose total scores and individual subject scores fall within specific thresholds.
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
struct PlayerProfile {
std::string username;
int lang;
int logic;
int phys;
int total;
};
int main() {
int totalPlayers;
if (!(std::cin >> totalPlayers)) return 0;
std::vector<PlayerProfile> players(totalPlayers);
for (int i = 0; i < totalPlayers; ++i) {
std::cin >> players[i].username >> players[i].lang >> players[i].logic >> players[i].phys;
players[i].total = players[i].lang + players[i].logic + players[i].phys;
}
for (int i = 0; i < totalPlayers; ++i) {
for (int j = i + 1; j < totalPlayers; ++j) {
// Compare total score difference
if (std::abs(players[i].total - players[j].total) <= 10) {
// Compare individual subject differences
bool isLangClose = std::abs(players[i].lang - players[j].lang) <= 5;
bool isLogicClose = std::abs(players[i].logic - players[j].logic) <= 5;
bool isPhysClose = std::abs(players[i].phys - players[j].phys) <= 5;
if (isLangClose && isLogicClose && isPhysClose) {
std::cout << players[i].username << " " << players[j].username << std::endl;
}
}
}
}
return 0;
}