Index
Structure
In C++, structures are user-defined data types that allow you to group together variables of different types under a single name. They provide a way to create more complex data structures by organizing related data items. Unlike an array, a structure can contain many different data types (int, string, bool, etc.).
Create a Structure
To create a structure, you use the struct
keyword followed by the structure’s name and declare each of its members inside curly braces.
struct { // Structure declaration
int myNum; // Member (int variable)
string myString; // Member (string variable)
} myStructure; // Structure variable
Access Structure Members
You can access the members of a structure using the dot (.
) operator followed by the member’s name
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
struct {
int myNum;
string myString;
} myStructure;
myStructure.myNum = 10;
myStructure.myString = "John Marcos";
cout << myStructure.myNum << "\n";
cout << myStructure.myString << "\n";
return 0;
}
Output:
10
John Marcos
One Structure in Multiple Variables
To use one structure in many variables, You can use a comma (,
).
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
struct {
string brand;
string model;
int year;
} myCar1, myCar2; // We can add variables by separating them with a comma here
// Put data into the first structure
myCar1.brand = "AUDI";
myCar1.model = "X7";
myCar1.year = 1998;
// Put data into the second structure
myCar2.brand = "BMW";
myCar2.model = "Z5";
myCar2.year = 1970;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
return 0;
}
Output:
AUDI X7 1998
BMW Z5 1970