Introduction

Hello, and welcome back! Are you ready for a new challenge? In this unit, we're stepping up a notch to tackle a complex yet intriguing task. It involves parsing complex strings into C++ unordered_maps and then updating them, which is a common requirement in many real-world tasks. So yes, this unit's session is going to be pretty pragmatic — just the way you like it!

Task Statement

This task involves transforming a given string into a nested unordered_map and updating a specific key-value pair within that map. The input string will take the form "Key1=Value1,Key2=Value2,...". When a part of the value is another key-value string, we create a nested unordered_map.

For example, the string "A1=B1,C1={D1=E1,F1=G1},I1=J1" should be transformed into the following nested unordered_map:

unordered_map<string, unordered_map<string, string>> dictionary = {
    {"A1", unordered_map<string, string>{
        {"", "B1"}
    }},
    {"C1", unordered_map<string, string>{
        {"D1", "E1"},
        {"F1", "G1"}
    }},
    {"I1", unordered_map<string, string>{
        {"", "J1"}
    }}
};

Your C++ function should parse this string into the above unordered_map, then update the value of the nested key F1 from G1 to some other value, say 'NewValue'. The function should ultimately return the updated unordered_map.

Step 1 - Setting Up the Function and Variables

First, set up the function and necessary variables:

#include <iostream>
#include <sstream>
#include <unordered_map>
#include <string>

std::unordered_map<std::string, std::unordered_map<std::string, std::string>> parse_string(const std::string& input_string) {
    std::unordered_map<std::string, std::unordered_map<std::string, std::string>> result_map;

    std::string key;  // to store the outer map key
    std::unordered_map<std::string, std::string> inner_map;  // to store the inner map
    bool in_inner_map = false;  // flag to check if we are inside an inner map
    size_t i = 0;  // to iterate through the string
Step 2 - Handling the Opening and Closing Braces

Next, handle the opening and closing braces. If an inner map is encountered, set the flag and prepare to parse it:

    while (i < input_string.size()) {
        if (input_string[i] == '{') {
            // Entering an inner map
            in_inner_map = true;
            i++; // Skip the '{'
        } else if (input_string[i] == '}') {
            // Exiting an inner map
            result_map[key] = inner_map;
            inner_map.clear();
            in_inner_map = false;
            i++; // Skip the '}'
            if (i < input_string.size() && input_string[i] == ',') {
                i++; // Skip the ',' after '}'
            }
        } 
Step 3 - Parsing Outer Map Key-Value Pairs

Handle parsing key-value pairs in the outer map:

        else if (!in_inner_map) {
            // Parsing key-value pairs in the outer map
            size_t equal_pos = input_string.find('=', i);
            size_t comma_pos = input_string.find(',', equal_pos);
            if (comma_pos == std::string::npos) comma_pos = input_string.size();

            key = input_string.substr(i, equal_pos - i);
            std::string value = input_string.substr(equal_pos + 1, comma_pos - equal_pos - 1);

            if (value.find('{') != std::string::npos) {
                // Value is a nested map, will be processed separately
                key = input_string.substr(i, equal_pos - i);
                i = equal_pos + 1; // Move forward to process the nested part
            } else {
                // Value is a simple string, add to result map
                result_map[key] = { {"", value} };
                i = comma_pos + 1; // Move past the comma
            }
        }
Step 4 - Parsing Inner Map Key-Value Pairs

Handle parsing key-value pairs inside the inner map:

        else if (in_inner_map) {
            // Parsing key-value pairs inside the inner map
            size_t equal_pos = input_string.find('=', i);
            size_t comma_pos = input_string.find(',', equal_pos);
            size_t brace_pos = input_string.find('}', equal_pos);

            // Determine the next delimiter that ends the current key-value pair
            size_t end_pos = std::min(comma_pos < brace_pos ? comma_pos : std::string::npos, brace_pos);
            if (end_pos == std::string::npos) end_pos = std::max(comma_pos, brace_pos);

            std::string inner_key = input_string.substr(i, equal_pos - i);
            std::string inner_value = input_string.substr(equal_pos + 1, end_pos - equal_pos - 1);
            inner_map[inner_key] = inner_value;

            i = end_pos;
            if (i < input_string.size() && input_string[i] == ',') {
                i++; // Skip the comma
            }
        }
    }

    return result_map;
}
Step 5 - Updating the Value in the Map

Now that we have the parsed unordered_map, we can move into the final phase of the task: updating a specific key-value pair. Here’s the function to update a value in the nested unordered_map:

void update_map(std::unordered_map<std::string, std::unordered_map<std::string, std::string>>& map, const std::string& key, const std::string& value) {
    for (auto& pair : map) {
        auto it = pair.second.find(key);
        if (it != pair.second.end()) {
            // Key found, update the value
            it->second = value;
            return;
        }
    }
}
Step 6 - Putting It All Together

Finally, we put everything together in one function to parse the string and update the value:

std::unordered_map<std::string, std::unordered_map<std::string, std::string>> parse_string_and_update_value(const std::string& input_string, const std::string& update_key, const std::string& new_value) {
    // Parse the input string into a nested unordered_map
    std::unordered_map<std::string, std::unordered_map<std::string, std::string>> map = parse_string(input_string);
    // Update the specific key-value pair
    update_map(map, update_key, new_value);
    return map;
}
Lesson Summary

Well done! You've completed an intensive hands-on session dealing with complex strings and nested unordered_maps in C++. This type of task often mirrors real-life scenarios where you process complex data and make updates based on particular criteria.

Now it's your turn to reinforce what you've learned in this unit. Try practicing with different strings and attempting to update various key-value pairs. With practice, you'll be able to apply these coding strategies to a wide range of problems. Happy coding!

In this updated lesson, the code includes detailed comments explaining each step, making it clear how the processing and parsing are working.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal