gpt4 book ai didi

c++ - 避免在 map/unordered_map 中进行多次查找

转载 作者:太空狗 更新时间:2023-10-29 20:01:58 25 4
gpt4 key购买 nike

假设我们有一个昂贵的函数将 string 映射到 int 并且想要在映射中缓存结果。

最简单的代码是

int mapStringToIntWithCache(std::string const& s) {
static std::unordered_map<std::string, int> cache;
if (cache.count(s) > 0) return cache[s];
else return cache[s] = myExpensiveFunction(s);
}

但这有 2 次查找。

所以我倾向于这样写

int mapStringToIntWithCache(std::string const& s) {
static std::unordered_map<std::string, int> cache;
size_t sizeBefore = cache.size();
int& val = cache[s];
if (cache.size() > sizeBefore) val = myExpensiveFunction(s);
return val;
}

这只有一次查找,但看起来有点笨拙。有没有更好的办法?

最佳答案

只需使用 std::map::emplace() 方法:

int mapStringToIntWithCache(std::string const& s) {
static std::unordered_map<std::string, int> cache;
auto pair = cache.emplace( s, 0 );
if( pair.second )
pair.first->second = myExpensiveFunction(s);
return pair.first->second;
}

关于c++ - 避免在 map/unordered_map 中进行多次查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48651434/

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