How to Create Array of Structs in C++
- Use C-Style Array Declaration to Create Fixed-Length Array of Structs
-
Use
std::vector
and Initializer List Constructor to Create Variable Length Array of Structs - Use Dynamic Memory Allocation to Create an Array of Structs in C++
- Conclusion
In C++, struct arrays are a powerful mechanism for organizing and managing related data. In this article, we will explore three distinct methods to create an array of structs: using C-style array declaration, std::vector
with the initializer list constructor, and dynamic memory allocation with new
/delete
or malloc
/free
.
Use C-Style Array Declaration to Create Fixed-Length Array of Structs
One way to create an array of structs in C++ is through the use of a C-style array declaration. C-style array declaration, denoted by the square brackets []
, is a method for creating arrays of a fixed size.
This method allows you to store elements of the same data type in contiguous memory locations. When dealing with structs, each element of the array will represent an instance of the struct.
Note that this method has a limitation: the declared array is a basic object devoid of built-in functions. However, on the positive side, it can offer enhanced efficiency and faster performance as compared to C++ library containers.
Let’s illustrate this with an example. Suppose we want to represent information about companies, including their name, CEO, income, and number of employees.
We can define a struct called Company
to encapsulate this information and then use a C-style array declaration to create an array of structs.
#include <iostream>
#include <string>
struct Company {
std::string name;
std::string ceo;
float income;
int employees;
};
int main() {
const int arraySize = 2;
Company comp_arr[arraySize] = {{"Intel", "Bob Swan", 91213.11, 110823},
{"Apple", "Tim Cook", 131231.11, 137031}};
for (const auto &arr : comp_arr) {
std::cout << "Name: " << arr.name << std::endl
<< "CEO: " << arr.ceo << std::endl
<< "Income: " << arr.income << std::endl
<< "Employees: " << arr.employees << std::endl
<< std::endl;
}
return 0;
}
In this example, we define a struct named Company
, which encapsulates information about a company. The struct contains data members for the company’s name, CEO, income, and number of employees.
struct Company {
std::string name;
std::string ceo;
float income;
int employees;
};
In the main
function, we declare a constant integer arraySize
to specify the size of our array of structs. We then declare an array of type Company
with a size equal to arraySize
.
The array is initialized with information about two companies using the curly brace initialization syntax.
const int arraySize = 2;
Company comp_arr[arraySize] = {{"Intel", "Bob Swan", 91213.11, 110823},
{"Apple", "Tim Cook", 131231.11, 137031}};
The subsequent for
loop iterates through the array, and for each element, it prints the company’s name, CEO, income, and number of employees to the console.
The output of the program will be:
Name: Intel
CEO: Bob Swan
Income: 91213.1
Employees: 110823
Name: Apple
CEO: Tim Cook
Income: 131231
Employees: 137031
In this output, you can see the organized information for each company within the array. The C-Style Array Declaration provides a simple and efficient way to manage structured data in C++.
Use std::vector
and Initializer List Constructor to Create Variable Length Array of Structs
When flexibility and dynamic sizing are necessary, using std::vector
along with the initializer list constructor provides a powerful alternative for creating an array of structs.
std::vector
is a dynamic array implementation in the C++ Standard Library. It can dynamically resize itself, making it a versatile choice for managing arrays.
When combined with the initializer list constructor, you can easily initialize and populate a vector in a single line of code. This is especially handy when dealing with structs, where you want to create an array and populate it with specific values at the same time.
Let’s explore this method by extending our example of managing information about companies using the Company
struct. Note that initializer list members must include outer curly braces for correct assignment and formatting.
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
struct Company {
string name;
string ceo;
float income;
int employees;
};
int main() {
vector<Company> comp_arr = {{"Intel", "Bob Swan", 91213.11, 110823},
{"Apple", "Tim Cook", 131231.11, 137031}};
for (const auto &arr : comp_arr) {
cout << "Name: " << arr.name << endl
<< "CEO: " << arr.ceo << endl
<< "Income: " << arr.income << endl
<< "Employees: " << arr.employees << endl
<< endl;
}
return 0;
}
In the code above, we introduce the <vector>
header to include the necessary functions for working with vectors. The Company
struct remains the same as in the previous example.
In the main
function, we declare a std::vector
named comp_arr
of type Company
. Using the initializer list constructor, we initialize and populate the vector with data for two companies.
The syntax involves enclosing each struct’s data within curly braces and separating individual structs with commas.
vector<Company> comp_arr = {{"Intel", "Bob Swan", 91213.11, 110823},
{"Apple", "Tim Cook", 131231.11, 137031}};
Subsequently, we utilize a for
loop to iterate through the vector. The loop variable arr
represents each element of the vector, which is an instance of the Company
struct.
We print the information about each company to the console using cout
.
Output:
Name: Intel
CEO: Bob Swan
Income: 91213.1
Employees: 110823
Name: Apple
CEO: Tim Cook
Income: 131231
Employees: 137031
The output illustrates that we’ve successfully created and accessed a dynamic array of structs using std::vector
and the initializer list constructor in C++. This approach enhances flexibility and simplifies the process of initializing and managing arrays, especially when the size is not known at compile time.
Use Dynamic Memory Allocation to Create an Array of Structs in C++
In scenarios where the size of the array needs to be determined at runtime or when working with a large number of elements, dynamic memory allocation provides an effective solution.
Dynamic memory allocation involves requesting memory from the heap during runtime, allowing for flexibility in managing memory. When dealing with structs, this method is particularly useful when the size of the array is unknown at compile time.
Memory can be allocated using new
or malloc
, and it should be released using delete
or free
when it is no longer needed to prevent memory leaks.
Let’s explore this approach using our example of managing company information with the Company
struct.
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
struct Company {
string name;
string ceo;
float income;
int employees;
};
int main() {
Company* comp_arr = new Company[2];
comp_arr[0] = {"Intel", "Bob Swan", 91213.11, 110823};
comp_arr[1] = {"Apple", "Tim Cook", 131231.11, 137031};
for (int i = 0; i < 2; ++i) {
cout << "Name: " << comp_arr[i].name << endl
<< "CEO: " << comp_arr[i].ceo << endl
<< "Income: " << comp_arr[i].income << endl
<< "Employees: " << comp_arr[i].employees << endl
<< endl;
}
delete[] comp_arr;
return 0;
}
In the code above, we start by including the necessary header files and defining the Company
struct. Within the main
function, we declare a pointer comp_arr
of type Company
, which will be used for dynamic memory allocation.
We allocate memory for two instances of the Company
struct using the new
operator. The array elements are then initialized with the company data.
Company* comp_arr = new Company[2];
comp_arr[0] = {"Intel", "Bob Swan", 91213.11, 110823};
comp_arr[1] = {"Apple", "Tim Cook", 131231.11, 137031};
It’s important to note that when using new
, the memory must be released using delete[]
to avoid memory leaks.
Subsequently, we loop through the array using a for
loop and print the information about each company to the console. Finally, we release the allocated memory using delete[] comp_arr
.
Output:
Name: Intel
CEO: Bob Swan
Income: 91213.1
Employees: 110823
Name: Apple
CEO: Tim Cook
Income: 131231
Employees: 137031
The output demonstrates the successful creation and access of an array of structs using dynamic memory allocation in C++. This method provides the flexibility to adjust the size of the array during runtime, making it particularly useful in situations where the size is unknown at compile time.
Conclusion
In conclusion, C++ provides various methods for creating arrays of structs, each catering to specific needs. Whether you require a static array, dynamic sizing, or runtime flexibility, these methods enable you to efficiently manage and manipulate structured data in your C++ programs.
Choose the method that aligns with your project requirements and coding preferences.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn FacebookRelated Article - C++ Struct
- C++ Anonymous Struct
- C++ Struct Default Values Initialization
- Difference Between Struct and Typedef Struct in C++
- Struct in Class in C++
- Struct Inheritance in C++