gpt4 book ai didi

c++ - 哈希表,其中键是字符串,值是 C++ 中的函数

转载 作者:行者123 更新时间:2023-11-28 02:54:41 25 4
gpt4 key购买 nike

是否可以实现哈希,其中键是 String,值是 function。对于背景,我有一个程序,其中有很多字符串比较,即

if(strcasecmp(s,"london")==0) 
functionA();
else if(strcasecmp(s,"moscow")==0)
functionB();
else if(strcasecmp(s,"delhi")==0)
functionC();
...

等等。

但是这种实现的成本非常高(theta(n)),因为String 比较是针对所有if 语句进行的。如果我们有一个散列实现,其中键是 String,值是 function,我们可以调用类似

的东西
function = hash.Get("moscow");    
function();

它的复杂度很好(theta(log(1)))

这有可能吗?

最佳答案

Is it possible to have an implementation for hash, where key is String and value is function?

是的。这是完全可行的。您可以使用指向函数或 std::function 的指针。可能的容器可能是:

  1. std::unordered_map
  2. boost::unordered_map

关于c++ - 哈希表,其中键是字符串,值是 C++ 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22276713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com