Home >Backend Development >C++ >How Do I Efficiently Access Values in a Nested C Map Using Iterators?

How Do I Efficiently Access Values in a Nested C Map Using Iterators?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 22:09:15375browse

How Do I Efficiently Access Values in a Nested C   Map Using Iterators?

Accessing Values in a Multi-Layered C Map Using Iterators

Iterating through a C map of maps, where the inner maps contain key-value pairs, can be achieved efficiently using iterators. Here's how you can do it:

Declare the map as follows:

std::map<std::string, std::map<std::string, std::string>> m;

To iterate through the outer map, use the following syntax:

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
  }
}

Example:

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;
}

Output:

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

The above is the detailed content of How Do I Efficiently Access Values in a Nested C Map Using Iterators?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn