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
Release: 2024-12-02 22:09:15
Original
312 people have browsed it

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;
Copy after login

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
  }
}
Copy after login

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;
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template