Home > Software engineering >  STD flexible data structure? c
STD flexible data structure? c

Time:09-02

I'm using nlohmann json objects, since they can add key-value pairs after runtime (and can readily be serialized)... Though I realize this may sacrifice speed.

Are there any data structures, of similar flexibility, that are from standard c libraries?

string character_new()
{
    json j;

    j["level"] = 1;
    j["max_hp"] = 2;
    j["hp"] = 2;

    j["skills"] = {
        {"atk", 1},
        {"dex", 1},
    };
    
    j["x"] = 1000;
    j["y"] = 1000;
    j["state"] = -1;
    j["map"] = map_get(MAP::forest);
    j["dead"] = false;
    j["name"] = "Some name";
    //etc

    return(j.dump());
}

CodePudding user response:

You have the building blocks in the standard but you would have to wrap them up as they will lack the niceties of nlohman and perhaps some functionality too, as serialization.

One general option would be using

using AnyMap = std::unordered_map< std::string, std::any >; 

However std::any is knowingly (and understandably) slow. If you can settle for some few types you can try

class Node;
using NodeMap = std::unordered_map<std::string,Node>;
using NodeSequence = std::vector<Node>;
class Node : public std::variant<NodeMap,NodeSequence,long,double,std::string> {};
  • Related