开发者

Dynamic Switch Case in C++

Is there a way I can build a dynamic switch case in C++. Actually the case values are known to me only at runtime and the number of those case values are also known only at runtime. The reason I'm doing this is that I'm trying to build a perfect hash lookup through this switch case at runtime. So for example, i have four values 89, 94, 38, 54, I want equivalent of something as follow.

switch( x )
{
case 89:
  return 0;
case 94:
  return 1;
case 38:
  return 2;
case 54;
  return 3;
}

However, this should be built at runtime. We can of course use a for loop and search to implement hash look up, but that would be ofcourse slower than switch cas开发者_如何学Pythone.


Sadly not, switch cases only accept values that are known constants at compile-time. Of course, if you simply use if and if else instead of switches, it will do what you want just fine.


You can accomplish what you are looking for with a hash table. The basic idea is to map 89, 94, 38 , 54 to the values 0, 1, 2, 3. The lookup will then be

i = 38;
return hashtable[i];  //returns 2. 

If you have a small upper limit on the largest value (say 99) this is just an array.

int hashtable[100];

For more complex scenarios you can use a hash function or preferably predefined hash table.


You want something called a jump table- in your case, built at run-time. This basically consists of an array of function objects which return the desired values, where you index into it with the key.

You can also use a hash map, which is less efficient if the range is relatively small, but definitely better off if the range is large.


No you cannot create a switch case dynamically at runtime. Instead you should represent your hash function using some algorithmic data structure that suits your needs and make the look ups in that.


I suggest a binary search of an array, or if your domain is small enough you could just do an array lookup.


A for loop with linear probing would not be an example of a hash table.

The standard thing to do would be to use the hash classes provided by boost, stl, and many other popular libraries. It will probably not be as fast as a switch, but will be far better than looping.


switch statements normally are optimized to a jump table at compile time, so there is no way this could work. They have to be compile time constants. (Can you use template metaprogramming to generate them in the compile phase?)


Use a hash map. If there were a faster method, people would use it as the standard map.

Also remember that premature optimisation is the root of all evil.


If you really want a perfect hash, I suggest you either use something like the cmph library, or implement it yourself (see this article for an example, implemented in python)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜