Adding Structs to Vectors in C++
Vectors are dynamic arrays in C++ that can be resized at runtime. This makes them incredibly versatile for storing collections of data. Structs, on the other hand, are user-defined data types that allow you to group related data together.
This article will walk you through the process of adding structs to vectors in C++.
Defining a Struct
First, we need to define our struct. Let's say we want to create a struct to store information about a book:
struct Book {
string title;
string author;
int yearPublished;
};
This struct Book
contains three members: title
, author
, and yearPublished
, all of which are strings and an integer respectively.
Creating a Vector of Structs
Now, let's create a vector to hold our Book
structs:
vector bookCollection;
This line declares a vector named bookCollection
that can store objects of type Book
.
Adding Structs to the Vector
To add a new Book
struct to the bookCollection
vector, we use the push_back()
method:
Book newBook;
newBook.title = "The Hitchhiker's Guide to the Galaxy";
newBook.author = "Douglas Adams";
newBook.yearPublished = 1979;
bookCollection.push_back(newBook);
This code creates a new Book
object named newBook
, sets its members to the desired values, and then adds it to the end of the bookCollection
vector.
Accessing Structs in the Vector
To access a specific Book
struct within the vector, we can use its index:
Book firstBook = bookCollection[0];
cout << firstBook.title << endl;
This code retrieves the first Book
struct in the vector (index 0) and prints its title to the console.
Iterating Through the Vector
You can easily iterate through the entire vector of structs using a loop:
for (int i = 0; i < bookCollection.size(); i++) {
cout << bookCollection[i].title << " by " << bookCollection[i].author << endl;
}
This code iterates through each Book
struct in the vector and prints its title and author.
Conclusion
Adding structs to vectors in C++ provides a powerful way to manage collections of complex data. By using the push_back()
method, you can easily add new structs to your vector. You can then access and modify the individual structs within the vector using their indices or by iterating through the vector using loops.