C++

Array of Structs C++

It is stated that arrays are containers that contain elements of the same data type.  What about those containers that have the elements of different data types? There exist such types of containers that contain dissimilar data. These are known as structures. For instance, if you want to save the information of a student in a school, you will save the information containing student id, name, marks, etc. All these variables will be of different data types like integer, character, and float. This topic will contribute to the details of structures and the arrays of structures as well.

Define a structure

A structure is a data type that the user defines. The syntax of the structure is written below.

Struct structurename{
    Data type variable;
    Data type variable2;
    Data type variable3;
};

In this sample, the keyword ‘struct’ is used with the name of a structure. And inside the structure body, we write the variables with their data types. And then, the structure body is closed with a semi-colon following the closing bracket. We will use an example here.

struct Book{
    char title;
    char Author_name;
    int year;
    float price;
};

Structure variable declaration

As we declare variables for different data types, the variables for structures are also declared. This declaration of variables is done in the main function. This is also said to be object creation. Let us take the data of two books in the structure. We can define the example as:

struct Book{
    Int year;
    Float price;
};
void main()
{   struct book b1, b2; }

These are the objects that are used to access the values present inside the structures. Moreover, these are also used to assign values in the variables. We also use another technique of creating the variables. Now let us observe how the values are assigned to the variables inside the structure. Suppose we want to enter the price of one book. This will be done by writing:

B1.price = 1500;

It reflects that we use (.) to use the object for accessing the variables. Similarly, the same approach can be applied here. You can access the variables and enter values in them. Now we will talk about creating arrays with structures. We can make arrays of structures; if we want to enter the data of the books of more than 1, then we use an array for that.

Example 1
Consider an example in which we have used an array of structures; first; we will use the library of iostream and string. Then we will introduce a structure for that with the name student. This structure has three attributes roll number, name, and phone number.

After that, write the main program; the first step will be creating objects of the structure through an array, so we will use an array of 5 elements as a sample.

struct student stud[5];

Now use a “For” loop to display the message to the user so that the user enters the values accordingly. Each value will be entered by using a dot method that joins the object with the variable. To enter the value at a specific index, we use the ‘I’ variable inside the loop.

cin >> stud[i].name;

After entering the values, we will display them again using the “for” loop. As a sample example, the loop will iterate for 3 times only. To check the output, we will use the Linux terminal. For the compilation, use a G++ compiler to execute C++ source codes. Save the file with a ‘.c’ extension.

$ g++ -o struct struct.c
$./struct

From the above image, it is clear that the system asks the user to enter the values when the code is executed. According to the loop, the iterations are completed; the values entered till now will be displayed as it is.

Example 2
This second example relates to the use of std::vector container. With the help of this, we declare a variable array, and this provides many built-in functions. Firstly, the library of a vector is added in the header file strings.

#include <vector>

It contains many features like cout, endl, vector, and string. A structure with a name company is created having 4 attributes of different data types. Here we have directly assigned the values of the variables.

vector <company> comp_arr ={}

Using this approach, each value will be directly assigned to the variables present at a specific address.

When all the values are entered, we will now display them by using a “for” loop. This is done by using a constant object of array “arr” with a dot method with each variable of the array. We will see the resultant values of the code by using the same compiler on the Ubuntu terminal.

Example 3
This example uses a structure to store the information of the movies. First, a library of a stream is used here to allow the “io” streaming with strings as well. This example includes the array of films having 3 elements. The structure contains two attributes, but the information will be taken 3 times.

A function is used to print the values the user will enter after the execution of the program.

void printmovie (movie_t movie);

In the main program, we will create an object for the string. It will take values from the console. Similarly, to get the value, we have used a string feature “getline”. This will take the value using “cin” and the variable with the number of films. For instance, for the first film details, the compiler will consider the value of [n] as 1.

getline (cin, films[n].title);

So the title for the first film will be entered this way. Similarly, for the year, we will also use the getline function. But this is done through the string stream as we have used the string stream in the libraries. Here in the parameter with ‘cin’ instead of the index number, the object of the string is used. And in the second line with the string stream, we will use the object to assign the value at the specific index variable in the structure.

getline (cin, mystr)
stringstream(mystr)>>films[n].year

To display the entered values, a function is used. For a function call, a “For” loop is used. In each iteration, the function call contains a different parameter regarding movies number having an index.  The parameter of the function call contains the array with the index number.

printmovie (films[n]);

Whereas the function will take the structure name and a new object to access the values inside the structure from the function. Use parenthesis to display the year adjacent to each movie name.

Now to see the resultant value, use the g++ compiler in the Ubuntu terminal. When the code is executed, the system will ask the user to enter the values. As the loop iterates 3 times, three movie names will be entered. And then, these values will be displayed.

Conclusion

“Array of structs C++” is an article that contains the basic knowledge of structures and arrays. The methodology of declaring structures in C++ is also discussed. Moreover, when to create an array of structure and its creation is deeply explained with the examples. We hope this topic under discussion will guide you in programming aspects.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.