c++ vector structure

To create a vector of structures in C++, you can follow these steps:

  1. Define the structure: Start by defining the structure using the struct keyword. For example, if you want to create a structure to hold information about a person, you can define it like this:
struct Person {
    std::string name;
    int age;
    std::string address;
};
  1. Declare the vector: Declare a vector of the structure type by specifying the structure name followed by angle brackets (<>). For example, to declare a vector of Person structures, you can do:
std::vector<Person> people;
  1. Add elements to the vector: Use the push_back() function to add elements to the vector. Each element should be of the structure type. For example, to add a person to the vector, you can do:
Person p1;
p1.name = "John";
p1.age = 25;
p1.address = "123 Main St";

people.push_back(p1);
  1. Access elements in the vector: You can access elements in the vector using the indexing operator ([]) or using iterators. For example, to access the first person in the vector, you can do:
Person firstPerson = people[0];

or

std::vector<Person>::iterator it = people.begin();
Person firstPerson = *it;
  1. Modify elements in the vector: You can modify elements in the vector by accessing them using the indexing operator or iterators, and then assigning new values to the structure members. For example, to change the age of the first person in the vector, you can do:
people[0].age = 30;
  1. Remove elements from the vector: You can remove elements from the vector using the erase() function, specifying the iterator to the element you want to remove. For example, to remove the first person from the vector, you can do:
people.erase(people.begin());
  1. Iterate over the vector: You can iterate over the vector using a for loop or iterators. For example, to iterate over the vector and print the names of all the people, you can do:
for (const auto& person : people) {
    std::cout << person.name << std::endl;
}

This is a basic overview of how to create and manipulate a vector of structures in C++. Remember to include the necessary headers (<vector> and <string>) at the beginning of your code to use the vector and string types.