realcohol 2018-01-26 23:24 采纳率: 0%
浏览 5679
已结题

关于C++中 unordered_map 中类成员的初始化

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class Testclass{
public:
    explicit Testclass();
private:
    std::unordered_map<std::vector<int>, int> world;
};

Testclass::Testclass() {
    std::vector<int> temp(5);
    world = {{temp,0}};
}

int main()
{
    Testclass testclass();
    return 0;
}

运行这段代码之后会报错,提示说implicit instantiation of undefined template 'std::__1::hash > >'
: public integral_constant {};
我觉得可能是构造函数中类成员变量member初始化的过程中出现了一些问题。求各位大神解答一下

  • 写回答

3条回答

  • lele570929726 2018-01-27 01:22
    关注

    std::unordered_map 使用hash函数组织数据结构,并实现相关操作。

    根据Cpp Reference - std::unordered_map, std::unordered_map 默认使用 std::hash 作为Hash函数的实现。

    根据Cpp Reference - std::hash, std::hash 对以下类型进行了特化:

    template<> struct hash<bool>;
    template<> struct hash<char>;
    template<> struct hash<signed char>;
    template<> struct hash<unsigned char>;
    template<> struct hash<char16_t>;
    template<> struct hash<char32_t>;
    template<> struct hash<wchar_t>;
    template<> struct hash<short>;
    template<> struct hash<unsigned short>;
    template<> struct hash<int>;
    template<> struct hash<unsigned int>;
    template<> struct hash<long>;
    template<> struct hash<long long>;
    template<> struct hash<unsigned long>;
    template<> struct hash<unsigned long long>;
    template<> struct hash<float>;
    template<> struct hash<double>;
    template<> struct hash<long double>;
    

    而你的代码中,对应的Key的类型为 std::vector ,而std::hash中并为对此类型进行特化,所以需要自己特化 std::hashstd::vector<int> 并实现相应的hash函数。

    评论

报告相同问题?