Using unordered_map on array of doubles

前端 未结 1 915
北荒
北荒 2021-01-16 06:47

My main data object is a array of doubles of a length that depends on a specific instantiation of my class. I would like to construct a very simple hash table to store/retr

相关标签:
1条回答
  • 2021-01-16 07:06

    One way would be to create struct to hold the pointer to the sequence of doubles:

    struct DoubleRegion
    {
        double* p;
        size_t size;
    };
    
    bool operator==(DoubleRegion a, DoubleRegion b)
    {
        return a.size == b.size && memcmp(a.p, b.p, a.size) == 0;
    }
    
    size_t hash(DoubleRegion dr) 
    {
        size_t h = 0;
        for (double* p = dr.p; p != dr.p + dr.size; ++p)
            h ^= hash(*p);
        return h;
    }
    

    And then use it:

    unordered_map<DoubleRegion, DoubleRegion> cache;
    

    Of course it is your problem to make sure the lifetime of the backing memory is a superset of the lifetime of the DoubleRegion.

    Old Answer:

    If you don't know until runtime how big the key and value is going to be, use a std::vector:

    unordered_map<vector<double>, vector<double>> cache;
    

    If you know at compile-time how big you can use an std::array:

    unordered_map<array<double, N>, array<double, N>> cache;
    

    In both cases the default hashing function will work by value as you want, and you do not need to define a custom one.

    0 讨论(0)
提交回复
热议问题