Vector of structs in C++

Vector of Structs in C++

In this article, we will see how to initialize and use vector of structs in C++.

There are different ways to do it. This article will explain these methods clearly.

Using Range Constructor

We can utilize the range constructor for the initialization of vector of structs in C++. It is useful when we need to make another copy of the existing vector. We will declare a different vector and copy the elements from the old vector using the range. We can access the elements of structs using ‘struct.element’ at the time of output.

Code:

Output

First Name: Steve
Last Name: Smith
Roll Number: 59
First Name: Shane
Last Name: Watson
Roll Number: 57
First Name: Adam
Last Name: Gilchrist
Roll Number: 3
First Name: Ricky
Last Name: Ponting
Roll Number: 43

Using Initializer list

It is a simple method to create a vector of structs in C++. Here we initialize the container with the constant values. This method is better when it is important to have an initial state of some type for data structure.

Code:

Output

First Name: Steve
Last Name: Smith
Roll Number: 59
First Name: Shane
Last Name: Watson
Roll Number: 57
First Name: Adam
Last Name: Gilchrist
Roll Number: 3
First Name: Ricky
Last Name: Ponting
Roll Number: 43

Using custom constructor

In this method, we create a vector specific constructor which will initialize the vector with a given number filled with different values. Here we will take input from the user and we create a custom vector of structs with different values.
Code:

Input

Enter the number of values you want to add:2
Please enter the first name, last name and roll number of a student:
Glenn
Maxwell
30
Please enter the first name, last name and roll number of a student:
David
Warner
21

Output

First Vector
First Name: Donald
Last Name: Bradman
Age: 32
First Name: Donald
Last Name: Bradman
Age: 32
Second Vector:
First Name: Glenn
Last Name: Maxwell
Age: 30
First Name: David
Last Name: Warner
Age: 21

Bonus Program

Program to sort a vector of structs in C++ according to the roll numbers of the students.

Code

Output

Original Vector Before Sorting:

72 Louis
78 Mike
26 Harvey
15 David

Vector After Sorting:

15 David
26 Harvey
72 Louis
78 Mike

Conclusion

In this article we demonstrated different methods that can create a vector of structs in C++. Custom Constructor method can be used in other ways as well as per the needs of the program.
Happy Learning!!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.