How could I get a C++ std::map to have multiple values

87 Views Asked by At

I'm trying to make a JSON parser in C++ and I need to get the std::map function to store any value, such as a bool, string, int, etc.

This is my (unfinished) code:

//stringX is a separate namespace that has only two functions (replace, and replace_all)
namespace json {
    void parse(std::string json) {
        stringX::replace_all(json, "{", "");
        stringX::replace_all(json, "}", "");
        size_t pos = 0;
        while ((pos = json.find(',', pos)) != std::string::npos) {
            if (json[pos + 1] == '"') {
                stringX::replace(json, ",", "\n", pos);
            }
            pos++;
        }
    }
}

What I'm trying to achieve is something like this:

std::map<std::string,(insert something here)> testMap;

testMap["first"] = true;
testMap["second"] = 1;
testMap["third"] = "hi!";

This doesn't work, since no type like this exists in C++. I could do this:

#include <any>

int main(){
    std::map<std::string, std::any> testMap;
    return 0;
}

but apparently "any" is undefined, so I tried the variant library instead:

#include <variant>

int main(){
    std::map<std::string, std::variant<(insert example types here)>> testMap;
    return 0;
}

Guess what? VARIANT is undefined too, so I resorted to StackOverflow. I found a question that had exactly what I was looking for - but I couldn't really understand this since I'm relatively new to C++: so I didn't really use that.

Any ideas on how I could do this? Also, please explain the concept to me if you have an answer.

0

There are 0 best solutions below