在C ++中的open adressing哈希表中实现emplace

时间:2017-07-17 02:59:10

标签: c++ template-meta-programming emplace

我正在实现一个这样的开放地址哈希表:

template <typename  K, typename V> 
class open_addressing_map
{
public:
    using key_type = K;
    using mapped_type = V;
    using value_type = std::pair<const key_type, mapped_type>;
    using hasher = std::hash<K>;
    using hash_code = std::size_t;
    using allocator_type = std::allocator<value_type>;

    value_type* buckets; //array of value, allocate at constructor
    std::size_t capacity; //capacity buckets
    hasher hash_func;
    allocator_type allocator;

private:
    std::pair<std::size_t, bool> find_internal(hash_code hash, const key_type& key);
    std::size_t find_free_bucket(hash_code hash);

public:
    template<typename ...Args>
    std::pair<iterator, bool> emplace(Args&& ...args) {
        //I need to construct a key_type in stack here to pass into find() and find_free_bucket
        //I don't want to construct a value_type because it can be expensive.
        key_type key = ...?; //how can I do this

        hash_code hash;
        hash = hash_func(key); 

        auto res = find(hash, key);
        //if not found
        if (!res.second) {
            std::size_t free_idx = find_free_bucket(hash);
            if (hash == capacity)
                return {iterator(capacity), false};
            else {
                //need to rehash then insert a gain.
            }
            //construct value
            allocator.construct(std::forward<Args&&>(args)...);
        }
    }

};

问题是我使用的是在构造函数中预先分配的容量,以减少分配开销。在emplace函数中,我需要找到正确位置来构造值,但在获得此位置之前需要密钥。

我可以在这里构建value_type以获取key但稍后,我必须将其移至buckets数组中的正确位置。

这个想法只是在堆栈中构造key,但我不知道该怎么做?

0 个答案:

没有答案