c++上的哈希聚合

Hash Aggregate on C++

本文关键字:哈希聚 c++      更新时间:2023-10-16

我试图在c++中实现一个散列聚合算法。

下面是伪代码:
for each input row
  begin
    calculate hash value on group by column(s)
    check for a matching row in the hash table // calculate hash function **(A)**
    if we do not find a match
      insert a new row into the hash table // calculate hash function again? **(B)**
    else
      update the matching row with the input row
  end
output all rows in the hash table

使用STL (c++), A行是:iter_type it=groupByMap.find(hashKey);所以我将支付一个查找,计算哈希值。

B将是:it = groupByMap.insert(it, newHashElement);所以我支付再次查找,计算哈希值。

是否有办法只执行一次哈希计算?

假设groupByMapstd::unordered_map<YOUR_KEY, YOUR_VALUE>,类型定义为YourMap

如果是,只需:

std::pair<YourMap::iterator, bool> position = 
    groupByMap.emplace(hashKey, newHashElement);
if (!position.second)
{
  // Insertion didn't occur, a key was already there, so just update contents.
  YourUpdate(*position.first);
}
在上面的代码中,我使用了std::unordered_mapemplace()方法。groupByMap.emplace(hashKey, newHashElement)本质上是groupByMap.insert(std::make_pair(hashKey, newHashElement)),但没有创建临时pair(它就地构建pair)。所以,如果你没有使用std::unordered_map,但其他类,如stl::hash_map,没有emplace(),你可以用insert()代替emplace()描述,它会正常工作。