map of vector of struct error
#include <iostream>
#include <vector>
#include <map>
struct Data {
int id;
std::string name;
};
int main() {
std::map<int, std::vector<Data>> myMap;
Data d1 = {1, "Alice"};
Data d2 = {2, "Bob"};
Data d3 = {3, "Charlie"};
myMap[101].push_back(d1);
myMap[101].push_back(d2);
myMap[102].push_back(d3);
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << std::endl;
for (const auto& data : pair.second) {
std::cout << "ID: " << data.id << ", Name: " << data.name << std::endl;
}
}
return 0;
}
Explanation:
Include Libraries: Include necessary libraries for input/output, vectors, and maps.
Define a Struct: Create a struct named
Data
with two members:id
of type integer andname
of type string.Main Function: The program's entry point.
Declare a Map of Vectors of Structs: Define a map named
myMap
where the keys are integers and the values are vectors ofData
structs.Create Data Instances: Define three
Data
instances namedd1
,d2
, andd3
, each containing an ID and a name.Insert Data into the Map: Add
d1
andd2
intomyMap
with key 101, andd3
intomyMap
with key 102. This creates vectors associated with keys 101 and 102 containing the respectiveData
elements.Iterate Through the Map: Use a for loop to iterate through each key-value pair in
myMap
.Print Key: Print the current key from the map.
Print Data within the Vectors: Use another loop to iterate through each
Data
element within the vector associated with the current key and print its ID and name.Return: End the program, returning 0 to indicate successful completion.