In C++, you can create a list of dictionaries using the `std::list` container for the outer list and `std::map` container for the inner dictionaries.
In this example,
list
and map
.dict1
and dict2
using the std::map
container.list_of_dicts
using the std::list
container and initialize it with the inner dictionaries.#include <iostream>
#include <list>
#include <map>
int main() {
std::map<std::string, std::string> dict1 = { {"key1", "value1"}, {"key2", "value2"} };
std::map<std::string, std::string> dict2 = { {"key3", "value3"}, {"key4", "value4"} };
std::list<std::map<std::string, std::string>> list_of_dicts = {dict1, dict2};
for (const auto& dict : list_of_dicts) {
for (const auto& pair : dict) {
std::cout << pair.first << "=" << pair.second << " ";
}
std::cout << std::endl;
}
return 0;
}
key1=value1 key2=value2 key3=value3 key4=value4
In this example,
list_of_dicts_empty
using the std::list
container.dict3
and dict4
using the std::map
container.push_back
method to add the inner dictionaries dict3
and dict4
to the outer list list_of_dicts_empty
.#include <iostream>
#include <list>
#include <map>
int main() {
std::list<std::map<std::string, std::string>> list_of_dicts_empty;
std::map<std::string, std::string> dict3;
std::map<std::string, std::string> dict4;
list_of_dicts_empty.push_back(dict3);
list_of_dicts_empty.push_back(dict4);
for (const auto& dict : list_of_dicts_empty) {
for (const auto& pair : dict) {
std::cout << pair.first << "=" << pair.second << " ";
}
std::cout << std::endl;
}
return 0;
}
In this tutorial, we learned How to create a List of Dictionaries in C++ language with well detailed examples.