【问题标题】:C++ 11 passing custom hash function into unordered_mapC++ 11 将自定义哈希函数传递给 unordered_map
【发布时间】:2020-08-23 09:06:14
【问题描述】:

我不确定我理解为什么会这样编译。

#include <iostream>
#include <iterator>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <unordered_set>
#include <algorithm>
#include <queue>
using namespace std;



void thing() {
    auto hash = [](const std::pair<int, int> &pair) {
        return std::hash<string>()(to_string(pair.first));
    };
    auto map = std::unordered_map<std::pair<int, int>, int, decltype(hash)>();
}


int main() {

}

我还没有将散列函数传递给构造函数——它如何知道散列一对的实现?

【问题讨论】:

标签: c++ dictionary hash


【解决方案1】:

它可以编译,因为 lambda 表达式的类型是匿名类 - 可以实例化(但请参阅下面的注释)。代码块就是那个类的operator()() 方法。此类由构造函数 std::unordered_map 实例化为默认参数值 - 使用 lambda 表达式的类型,即模板参数:

unordered_map( InputIt first, InputIt last,
               size_type bucket_count = /*implementation-defined*/,
               const Hash& hash = Hash(), /* <<<< INSTANTIATION HAPPENS HERE */
               const key_equal& equal = key_equal(),
               const Allocator& alloc = Allocator() );

有关 lambda 表达式本质的更多信息,请参阅这个 SO 问题:

What is a lambda expression in C++11?


注意:正如评论者所指出的,您的代码 doesn't actually compile with C++11,因为由 lambda 表达式定义的匿名类的隐式默认构造函数在 C++11 中被删除。这在 C++20 中已更改:非捕获 lambda 获取默认构造函数,因此现在代码可以编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多