Passing a function to a template object during template initialization in C ++

I am trying to write an implementation for a hash map, I am not allowed to use anything from stdlib except iostream, string and cassert.

It should be general, so the values ​​that fill the buckets can be of any type. I need templates for this, but I just can’t pass the hash function. This will be the header file:

template<typename Value, typename hashFunction>
class hashTable{
    public:
      hashTable(int size){
        //Creates an empty vector of size on the table
      }
      define(Value v){
        loads value in Vector[hashFunction(v)];
      }
      ...
    private:
      Vector with all the elements
}

Note. I don’t think I need key templates, do I?

I cannot define a hash function inside my class because I would have to create one that works with all types (string from int, int to int, double to int, etc.). Therefore, I assume that the only solution is to pass the function as an argument in my main one. That would be the main thing.

int hashF(int v){return v}
int main(){
  hashTable<int,int,hashF> table(5);
}

, g++ " , hashF". , , , . ?

+4
2

. hash.h:

template<typename C, typename D, typename H>
class Tabla {
public:
Tabla(int s){
    cout << hashF(3) << endl;
    size=s;
}
private:
    H hashF;
    int size;
};

My hash.cpp

struct KeyHash {
unsigned long operator()(const int& k) const
{
    return k % 10;
}
};
int main(){
    Tabla<int,int,KeyHash> tab(3);
    return 0;
}

- , , , KeyHash.

, .

0
template<typename Value, int(*fun)(Value)>
class hashTable {
  std::vector<Value> v;
public:
  hashTable(std::size_t size) : v(size) { }
  void define(Value &&val) { v[fun(val)]  = val; }
};

Live Demo

:

template<typename Value, typename F>
class hashTable {
  std::vector<Value> v;
  F fun;
public:
  hashTable(std::size_t size, F fun_) : v(size), fun(fun_) { }
  void define(Value &&val) { v[fun(val)]  = val; }
};

Live Demo

+1

Source: https://habr.com/ru/post/1616981/


All Articles