2013-10-31 25 views
1

首先,我想告诉你,我的整体/主要针对的是使用它们的功能名称(字符串)作为参数来执行某些功能,我定义的函数如下: (我想生成用于我插入作为参数传递给函数的每个字符串数据的唯一号码)性能stdext ::哈希值()中定义的std ::的hash_set

#include <iostream> 
    #include <string> 
    #include <hash_set> 

    using namespace std; 
    void Func_Execution(string &s){ 
     int k=stdext::hash_value(s); 
    #if(_MSC_VER ==1500) 
     switch (k) 
     { 
     case -336300864: GETBATTERYCALLSIGNS(); 
      break; 
     case -1859542241:GETGUNIDS(); 
      break; 
     case 323320073:Foo(); // here int k=323320073 for string s="Foo" 
      break; 
     case 478877555:Bar(); 
      break; 
      defalut :Exit(); 
       break; 
     } 
    #endif 
    } 

在这里,我打电话Func_Execution功能如下:

void main(){ 
string s="Foo"; 
Func_Execution(s); 
} 

欲知道这是否有效(考虑性能/时间)消费)和有效的机制,为特定的字符串(字符模式)生成一个唯一的数值,而不是使用stdext :: hash_value()函数?(另外注意我也想实现开关情况)

+0

那'#endif'是错误的。 –

+0

谢谢你..我的不好:| –

+0

另外,你确定'hash_value'函数将为某个字符串* always *返回相同的散列吗?即使你更新了编译器/库?在所有支持的平台上? –

回答

1

你有没有考虑过类似

#include <functional> 
#include <iostream> 
#include <unordered_map> 
#include <string> 

using std::cout; 
using std::endl; 
using std::function; 
using std::string; 
using std::unordered_map; 

class Registry { 
public: 
    static void Execute(const string& function) { 
    if (functions_.find(function) != functions_.end()) { 
     functions_[function](); 
    } 
    } 
    static int Register(const string& function_name, function<void()> f) { 
    functions_.emplace(function_name, f); 
    return functions_.size(); 
    } 
    static void Dump() { 
    for (auto& i : functions_) { 
     cout << i.first << endl; 
    } 
    } 
private: 
    Registry() {}; 
    static unordered_map<string, function<void()>> functions_; 
}; 

unordered_map<string, function<void()>> Registry::functions_; 

#define REGISTER_FUNCTION(F) \ 
    namespace { \ 
    const int REGISTERED__##F = Registry::Register(#F, &F); \ 
    } 

void foo() { 
    cout << "foo" << endl; 
} 

REGISTER_FUNCTION(foo); 

void bar() { 
    cout << "bar" << endl; 
} 

REGISTER_FUNCTION(bar); 

int main() { 
    Registry::Execute("foo"); 
    Registry::Execute("foo"); 
    Registry::Execute("unknown"); 
    Registry::Dump(); 
    return 0; 
} 

它应该适合您的使用情况。我只是把它一起砍了,可能有一个bug,但它编译和运行(C++ 11)。

+0

能力,但它依赖于C++ 11,在这里,我要处理的VSC + V90/V100 :( –

+1

唯一C++ 11的依赖关系是unordered_map和std ::功能可以很容易地除去。 – user1233963

+0

@BuddhikaChaturanga添加在'无效的typedef(* void_function)(空隙)'和与'void_function替换'函数' ',并且使用'functions_ [function_name] = f;'而不是emplace变体。你可以用map或者随同编译的许多hash_map实现中的一个替换unordered_map RS。其他一切正常。 – Charlie

0

不要使用指纹哈希值()(这是你所描述的)。如果您事先了解所有可能的字符串,请使用您自己的perfect hash函数,然后测量结果以查看它是否值得。