使用迭代器访问多层 C 映射中的值
迭代映射的 C 映射,其中内部映射包含 key-值对,可以使用迭代器有效地实现。操作方法如下:
按如下方式声明映射:
std::map<std::string, std::map<std::string, std::string>> m;
要迭代外部映射,请使用以下命令语法:
for (auto& outer_entry : m) { std::string outer_key = outer_entry.first; std::map<std::string, std::string>& inner_map = outer_entry.second; // Iterate through the inner map using a nested loop for (auto& inner_entry : inner_map) { std::string inner_key = inner_entry.first; std::string inner_value = inner_entry.second; // Access the inner values here } }
示例:
m["name1"]["value1"] = "data1"; m["name1"]["value2"] = "data2"; m["name2"]["value1"] = "data1"; m["name2"]["value2"] = "data2"; m["name3"]["value1"] = "data1"; m["name3"]["value2"] = "data2"; for (auto& outer_entry : m) { std::cout << "Outer Key: " << outer_entry.first << std::endl; for (auto& inner_entry : outer_entry.second) { std::cout << "Inner Key: " << inner_entry.first << " - Value: " << inner_entry.second << std::endl; } std::cout << std::endl; }
输出:
Outer Key: name1 Inner Key: value1 - Value: data1 Inner Key: value2 - Value: data2 Outer Key: name2 Inner Key: value1 - Value: data1 Inner Key: value2 - Value: data2 Outer Key: name3 Inner Key: value1 - Value: data1 Inner Key: value2 - Value: data2
以上是如何使用迭代器有效地访问嵌套 C 映射中的值?的详细内容。更多信息请关注PHP中文网其他相关文章!