frozen icon indicating copy to clipboard operation
frozen copied to clipboard

Allow modification of map values

Open peter-moran opened this issue 3 years ago • 7 comments

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;

peter-moran avatar Nov 06 '20 05:11 peter-moran

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';

serge-sans-paille avatar Nov 06 '20 06:11 serge-sans-paille

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.

peter-moran avatar Nov 06 '20 13:11 peter-moran

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.

peter-moran avatar Nov 06 '20 14:11 peter-moran

Here's some rough example code https://github.com/peter-moran/frozen/pull/1

peter-moran avatar Nov 06 '20 15:11 peter-moran

Oh interesting. Indeed the value does not take part in the computation of the keys, so it's legit to think about it.

serge-sans-paille avatar Nov 06 '20 19:11 serge-sans-paille

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.

peter-moran avatar Nov 06 '20 19:11 peter-moran

Closed by #106

peter-moran avatar Nov 24 '20 02:11 peter-moran