C++ Long switch statement or look up with a map?
c++, dictionary, std, stdmap, switch-statement
Solution
Personally, I would use the map, as its use implies a data lookup - using a switch usually indicates a difference in program behavior. Furthermore modifying the data mapping is easier with a map than with a switch.
If performance is a real issue, profiling is the only way to get a usable answer. A switch may not be faster if branch mispredictions happen often enough.
Another approach to think about this is if it wouldn't make more sense to combine the code and the associated value into a datastructure, especially if the range of codes and values is static:
struct Code { int code; int value; };
Code c = ...
std::cout << "Code " << c.code << ", value " << c.value << std::end;
Problem
In my C++ application, I have some values that act as codes to represent other values. To translate the codes, I've been debating between using a switch statement or an stl map. The switch would look something like this: ``` int code; int value; switch(code) { case 1: value = 10; break; case 2: value = 15; break; } ``` The map would be an `stl::map<int, int>` and translation would be a simple lookup with the code used as the key value. Which one is better/more efficient/cleaner/accepted? Why?