Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
11 years, 2 months ago.
Creating a static lookup table
I have some named numbers that never change during the life time of my program which I need to be able to lookup by name. Since these name value pairs never change I want to define then either using the define compiler directive or as const so they get stored in flash and not use up the RAM.
So far the best I have come up with is to define all the constants then create a map in memory and fill it with the constants, e.g.
#include <string> #include <map> #define X0 "X0" #define X0I 200 class SomeClass { map<string, int> m; SomeClass() { m[X0] = X0I; } }
I know c++ 11 allows you to fill a map at the point its created, some thing like:
const map<string,int> myMap = { {"X0", 2}, {"X1", 4}, {"X2", 6} };
But doesn't look like mbed supports this at the moment.
Does anyone know of a good way of doing this on an mbed?
2 Answers
11 years, 2 months ago.
Hi,
Here is a simple solution :
const int table[] = { 2, 4, 6}; int lookup(const char *s) { return table[atoi(&s[1])]; } int main() { printf("%d\n", lookup("X0")); return 0; }
Thanks for the response. I've not used the 'atol' function before, I'm new to c++, but presumably the result of calling atol has to map to the correct point in the array meaning that the string must have some intrinsic link to the point in the array. I want to use any arbitrary string as the key, would this solution support that?
posted by 19 Sep 201311 years, 2 months ago.
Or:
const struct map { char *str; int num; } myMap[] = { {"X0", 2}, {"X1", 4}, {"X2", 6} };
But I'm not so sure that 'const' variables are actually stored in flash. E.g. in WINAVR you need quite some attributes and functions to achieve that.