How would I make an "object" (key-value pair) in C++?

73 Views Asked by At

I'm working with Arduino. I want to make an "object". By that, I mean a key-value pair (I'm used to Javascript, all you JS programmers know what I mean). Basically, I want to use something similar to JSON in C++.

I will show you how I would approach my problem if I were using JavaScript:

const timeZones = {
    "London": 0,
    "Paris": 1,
    "Sydney": 10,
    "Los Angeles": -8
}

And then I could access a value like this:

let pst = timeZones["LosAngeles"] * 3600;

I'm not sure how to do this in C++, though. I looked everywhere, and I could only find things about structs and 2d arrays, which are irrelevant to my problem.

I also found something really close to what I need, but it was a struct in an array or something like that (e.g. timeZones[3].time would give me -8).

Sorry if this is a super basic question, I just started Arduino 3 days ago.

1

There are 1 best solutions below

0
KIIV On

For Arduinos the answer depends on which board are you using.

The ARM based ones have full STL support so map/unordered_map will work. Just add the map or unordered_map header and you can use it like that.

#include <map>

std::map<std::string, int> timezones {
    { "London", 0 },
    { "Paris",  1 },
    { "Sydney", 10},
    {"Los Angeles", -8},
};

void loop() {
    Serial.println(timezones["London"]);
}

On AVR based ones (oldest ones Uno, nano, micro) there is no builtin STL suport, but there are some implementations like ArduinoSTL or Arduino_AVRSTL libraries, but both currently failed to link due to multiple definition of 'std::nothrow' so you'll have to fix this or make your own implementation in a style of array of structs and implement lookup for it.

Do you even need that? Some constants might be so much better than relatively costly string lookups:

constexpr int TZ_LONDON = 0;
constexpr int TZ_PARIS  = 1;

...

    Serial.println(TZ_PARIS);