vector of structs c++

To create a vector of structs in C++, follow these steps:

  1. Define the struct: Begin by defining the structure of the struct. This can be done using the "struct" keyword, followed by the name of the struct and a set of curly braces. Inside the curly braces, define the members of the struct, along with their data types. For example:
struct MyStruct {
    int id;
    std::string name;
    float salary;
};
  1. Declare a vector: Declare a vector of the struct type. This is done by specifying the data type as the struct name, followed by angle brackets ("<" and ">") and the keyword "vector". For example:
std::vector<MyStruct> myVector;
  1. Add elements to the vector: Use the "push_back()" function to add elements to the vector. This function appends an element to the end of the vector. Create instances of the struct and assign values to its members, then use the "push_back()" function to add the struct to the vector. For example:
MyStruct struct1;
struct1.id = 1;
struct1.name = "John";
struct1.salary = 1000.0;

myVector.push_back(struct1);
  1. Access elements in the vector: Use the square bracket syntax to access elements in the vector. Specify the index of the element you want to access within the square brackets. For example, to access the first element in the vector:
MyStruct firstElement = myVector[0];
  1. Iterate over the vector: Use a loop to iterate over the elements in the vector. You can use a range-based for loop or a traditional for loop with an index variable. For example, using a range-based for loop:
for (const MyStruct& element : myVector) {
    // Do something with each element
}

That's it! You have now created a vector of structs in C++. You can add, access, and iterate over the elements in the vector as needed. Remember to include the necessary headers at the beginning of your code, such as <vector> and <string>, to use vectors and strings in C++.