std::unordered_map<int,float> 是否仍然需要散列整数才能得到值?

Does std::unordered_map<int,float> still have to hash the integer to get to the value?

我想知道 std::unordered_map< int, float > 是否仍然需要对给定的整数进行哈希处理才能得到该值,或者直接使用它。我需要每秒多次快速执行此操作,并且由于 std::hash<int> 不能保证是恒等函数,我将如何重新定义它? (显然不使用 STL 并编写我自己的容器是可能的,但我怀疑我编写的那些容器是否会更有效率(可能慢得多,慢得多))。 谢谢!

I would like to know whether std::unordered_map< int, float > still has to hash the given integer

是的。

I need to perform this operation very fast many times

您是否完成了您的项目并见证了这是它的瓶颈?如果不是,请当心,因为您可能最终成为过早优化的受害者!

how would I go about redefining it?

那你得自己写代码了。示例:C++ unordered_map using a custom class type as the key,您将在此处使用 struct Key { int value; };.

我非常怀疑是否有任何理智的编译器会以直通方式以外的任何其他方式进行处理。即使那样,您也必须测试它是否有任何实际的不利性能影响(如果他们这样做,他们可能有充分的理由 - 例如,他们的哈希函数旨在与他们的 unordered_map 一起使用)。如果你想强制你的哈希函数,你可以有:

struct Key{
 int value;
};

然后查看 this answer 以检查如何使其与 unordered_map 一起使用。