Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Long switch statement or look up with a map?

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?

like image 699
Rachel Avatar asked Mar 17 '10 20:03

Rachel


People also ask

Is a switch case faster than a map?

So in general , switch is faster. The difference between map and switch is that : Map can be built dynamically while switch can't. Map can contain any arbitrary type as a key while switch is very limited to c++ Primitive types (char , int , enum , etc...).

Can we use long in switch case in C?

No, unlike Java, C permits that the control statement of a switch statement be any integer type. This includes int , long , unsigned long , uint32_t and pretty much any other integral type defined in the standard.

What is the use of switch statement in C?

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.


2 Answers

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; 
like image 88
Lars Avatar answered Sep 30 '22 19:09

Lars


If your codes are contiguous enough and their range permit you would be much better of with old-fashioned straightforward array, something like

int lookup[] = {-1, 10, 15, -1 222}; 

then the switch statement can be rewritten as simply as

value = lookup[code];

all other options introduce additional cost to some extent.

like image 37
Oleg Zhylin Avatar answered Sep 30 '22 19:09

Oleg Zhylin