1

i want to use map to save my data.

because my function is a member function, and i marked it as const.

So, when i want to get value, i can only use map.at(key)

but when the key is missing , i will get a const std::out_of_range & e error.

For this case, i design a macro:

#include <map>
#include <stdio.h>
#include <string>

#define START_MAP try {
#define END_MAP(s) \
} catch (const std::out_of_range & e) {\
  printf("%s map at crashed\n", s.c_str());\
  exit(1);\
}\

int main() {
  std::map<std::string, int> m;
  START_MAP;
  std::string b = "test";
  int a = m.at(b);
  END_MAP(""); // TODO: how can i get b here??
}

but i want to know the key name in my printf message, how can i get it?

nick
  • 832
  • 3
  • 12
  • _but i want to know the key name_ You cannot get a name of a variable at run-time except you store it into a string at compile-time. But, there is in fact a pre-processor option for this: the stringize operator. So, if you use `#s` in `END_MAP(s)` you will get the contents of `s` as C string. So, you could use it as `END_MAP(b)`. – Scheff's Cat May 19 '21 at 05:36
  • Did I already mention that macros are bad in C++, and specifically macros with unbalanced parentheses of any kind? ;-) – Scheff's Cat May 19 '21 at 05:37
  • FYI: [cppreference.com: # and ## operators](https://en.cppreference.com/w/cpp/preprocessor/replace#.23_and_.23.23_operators). Btw. [assert()](https://en.cppreference.com/w/cpp/error/assert) is a well-known macro which uses this trick to replicate the tested expression as string in its error output. I once made a `DEBUG()` macro for demo code which prints and executes the same piece of code at once: [DEBUG() on coliru](http://coliru.stacked-crooked.com/a/1a9d5e9a14281daf) – Scheff's Cat May 19 '21 at 05:42
  • And you maybe you should check on key existance rather than catch key unexistance. A lot of examples how achive this goal is [here](https://stackoverflow.com/questions/1939953/how-to-find-if-a-given-key-exists-in-a-c-stdmap) – Deumaudit May 19 '21 at 06:30
  • what's wrong with a function int getOrCrash(const std::map map, const std::string& key)? you can template it if you like to make it more general – Alessandro Teruzzi May 19 '21 at 06:41
  • @AlessandroTeruzzi i am very time sensitive, so, i want to try my best to speed up – nick May 19 '21 at 06:42
  • how much do you think a function call will cost you? Have you profiled it? btw, in my comment the map should be a reference (typo) – Alessandro Teruzzi May 19 '21 at 07:06

0 Answers0