frozen
frozen copied to clipboard
Allow modification of map values
Is it possible, or could it be possible, for this library to let you modify the values in a map? In particular, to maintain the perfect hashing of keys and the fact that there is a constant number of keys, but add the ability to update the values associated with the keys.
Toy example:
constexpr frozen::unordered_map<frozen::string, int, 2> fruits = {
{"n_apples", 0},
{"n_pears", 0},
};
fruits["n_apples"] = 10;
fruits["n_pears"] = fruits["n_apples"] * 2;
Well, this would be incompatible with the constexpr
keyword, as a constexpr
variable is readonly.
Would you write the following?
constexpr char data[3] = "yo";
data[1] = 'a';
Sorry, my example was bad. I did not mean for the map to be constexpr
. Here's a better example:
#include <frozen/set.h>
#include <frozen/string.h>
#include <frozen/unordered_map.h>
int main() {
frozen::unordered_map<frozen::string, int, 2> fruits = {
{"n_apples", 0},
{"n_pears", 0},
};
fruits.at("n_apples") = 10;
fruits.at("n_pears") = fruits.at("n_apples") * 2;
}
I see this does not compile, answering my question if it currently works or not.
At a technical level, do you see any reason this could not work? I may be interested in doing it myself.
With a little modification of the code this example is possible.
In particular, it just needs a version of at
and lookup
that does not return a const reference.
Here's some rough example code https://github.com/peter-moran/frozen/pull/1
Oh interesting. Indeed the value does not take part in the computation of the keys, so it's legit to think about it.
If it helps to explain why I am interested in this: I work on a lot of embedded projects where I would love to have a map that does not require dynamic allocation. In most cases I know the keys ahead of time (eg a list of enums or specific strings) but want to change the values associated with those keys over time. Typically for enums I just use an array and use the enums as the array index, but I find it very messy (and it only works with things that implicitly convert to unique integers).
In other words, as it stands this library provides a constexpr map, but with a little work it could also provide a fixed size map (or perhaps I would call it an associative array due to its fixed size nature) that allows runtime modification of values.
Closed by #106