Structures
C++ Structures
In C++, a structure is a user-defined data type that allows you to group together variables of different data types under a single name. Structures provide a way to organize related data and are often used to represent records or entities in a program.
Example:
#include <iostream>
#include <string>
// Define a structure named "Person"
struct Person {
// Member variables (data members)
std::string name;
int age;
double height;
};
int main() {
// Declare a variable of type "Person"
Person person1;
// Access and modify the member variables
person1.name = "John";
person1.age = 25;
person1.height = 1.75;
// Display information
std::cout << "Name: " << person1.name << std::endl;
std::cout << "Age: " << person1.age << std::endl;
std::cout << "Height: " << person1.height << " meters" << std::endl;
return 0;
}
In this example, we define a structure named Person
with three member variables: name
, age
, and height
. We then declare a variable of type Person
named person1
and use it to store information about an individual.
Initialization of Structure:
Person person2 = {"Alice", 30, 1.65};
Nested Structures:
// Define a nested structure
struct Address {
std::string street;
std::string city;
std::string country;
};
// Define a structure with a nested structure
struct Employee {
std::string name;
int age;
Address address; // Nested structure
};
int main() {
// Declare and initialize an employee
Employee employee1 = {"Bob", 28, {"123 Main St", "Cityville", "Countryland"}};
// Access and display information
std::cout << "Name: " << employee1.name << std::endl;
std::cout << "Age: " << employee1.age << std::endl;
std::cout << "Address: " << employee1.address.street << ", " << employee1.address.city << ", "
<< employee1.address.country << std::endl;
return 0;
}
Array of Structures:
// Define a structure for a book
struct Book {
std::string title;
std::string author;
int year;
};
int main() {
// Declare an array of books
Book library[3];
// Initialize the array elements
library[0] = {"The Catcher in the Rye", "J.D. Salinger", 1951};
library[1] = {"To Kill a Mockingbird", "Harper Lee", 1960};
library[2] = {"1984", "George Orwell", 1949};
// Display information about each book
for (int i = 0; i < 3; ++i) {
std::cout << "Title: " << library[i].title << std::endl;
std::cout << "Author: " << library[i].author << std::endl;
std::cout << "Year: " << library[i].year << std::endl;
std::cout << std::endl;
}
return 0;
}
Structures provide a way to organize and encapsulate related data, improving the clarity and maintainability of your code. They are a fundamental building block in C++ programming.