I'm probably trying to achieve the impossible, but StackExchange always surprises me, so please go through:
I need to match the name with an integer. Names (about 2k) are unique. There will be no additions or exceptions to this list, and the values ββwill not change at run time.
Implementing them as const int variables gives me a compile-time check for existence and type. It is also very clear and verbose in code. Errors are easily detected.
Implementing them as std::map<std::string, int> gives me great flexibility to create names for searches using string manipulations. I can use this to provide strings as parameters for functions that can query a list for multiple values ββby adding prefix / suffixes to this string. I can also iterate over multiple values ββby creating the digital part of the key name from a loop variable.
Now my question is: is there a way to combine both benefits? Missing compile-time checking (especially for key existence) almost kills the second method for me. (Moreover, std::map silently returns 0 if the key does not exist, which makes it difficult to find errors.) But the possibilities of adding a loop and a preliminary / suffix are so useful.
I would prefer a solution that does not use any additional libraries, such as boost, but please offer them all the same, since I could reimplement them.
An example of what I'm doing with the map:
void init(std::map<std::string, int> &labels) { labels.insert(std::make_pair("Bob1" , 45 )); labels.insert(std::make_pair("Bob2" , 8758 )); labels.insert(std::make_pair("Bob3" , 436 )); labels.insert(std::make_pair("Alice_first" , 9224 )); labels.insert(std::make_pair("Alice_last" , 3510 )); } int main() { std::map<std::string, int> labels; init(labels); for (int i=1; i<=3; i++) { std::stringstream key; key << "Bob" << i; doSomething(labels[key.str()]); } checkName("Alice"); } void checkName(std::string name) { std::stringstream key1,key2; key1 << name << "_first"; key2 << name << "_last"; doFirstToLast(labels[key1.str()], labels[key2.str()]); }
Another goal is that the code shown in the main() procedure remains as simple and detailed as possible. (Non-programmers need to understand.) The init() function will be generated by some tools code. The doSomething(int) functions doSomething(int) fixed, but I can write wrapping functions around them. Helpers like checkName() can be more complex, but they need to be easily debugged.