2017-06-07 11 views
0

ここでは、その頂点がユーザ定義クラスになるというマップを作ろうとしました。しかし、テンプレート型要素をunordered_setに追加しようとすると、エラーが発生します。コードは次のとおりです。テンプレートタイプをハッシュする

#include <iostream> 
#include <unordered_set> 
#include <string> 
#include <vector> 
#include <functional> 

template<class T> class Edge; 

template<class T> class Vertex{   // Made it a class just for its constructor. 
    public: 
     template<class A> Vertex(A vert){ 
      A vertex = vert; 
      std::unordered_set<Edge<A>> adjlist; 
     } 
}; 

template<class T> class Edge{  // Made it a class just for its constructor. 
    public: 
     template<class A> Edge(Vertex<A> vert1, Vertex<A> vert2, int w){  
      Vertex<A> *origin = &vert1; 
      Vertex<A> *target = &vert2; 
     } 
    }; 


template<class T> 
class WUG{ 
    private: 
     std::unordered_set<Vertex<T>> vertices; 
     std::unordered_set<Edge<T>> edges; 
     int num_of_edges; 
     int num_of_vertices; 
    public: 
     WUG() { 
      num_of_edges = 0; 
      num_of_vertices = 0; 
     } 
     void addVertex(T newVert) { 
      Vertex<T> temp = Vertex<T>(newVert);    
      vertices.emplace(temp);     //Problem is here 
     } 
int main(int argc, char** argv) { 
    WUG<char> g1 = WUG<char>(); 
    g1.addVertex('A'); 
    g1.addVertex('B'); 
    g1.addVertex('C'); 

    return 0; 
} 

エラー:それはhashtable_policy.hを開き、どのようにunordered_setするテンプレート型オブジェクトを据え付けるん

template <typename _Key, typename _Hash> 
     struct __is_noexcept_hash : std::integral_constant<bool, 
     noexcept(declval<const _Hash&>()(declval<const _Key&>()))> //Here 
    { }; 
    [Error] no match for call to '(const std::hash<Vertex<char> >) (const Vertex<char>&)' 

でエラーになりますか? 2 テンプレートのペアはどうですか?

答えて

1

ハッシュセット(または私の場合はハッシュマップ)を機能させるために特別なハッシュ関数と比較関数を用意する必要があると思います。ここには最小の例があります。 C++ 11でテスト済み彼らがfooではなくWRT Tをしているが、本人が同じでなければなりません - 私のハッシュと平等の機能の両方が全く制限するものではないことを

#include <unordered_map> 
#include <iostream> 
#include <algorithm> 

template<typename T> 
struct foo { 
    typedef T value_type; 
    foo(T x) : x(x) {} 
    T x; 
}; 

template<typename T> 
struct foo_hasher { 
    int operator()(const T &val) const { 
    return std::hash<typename T::value_type>()(val.x); 
    } 
}; 

template<typename T> 
struct foo_equality { 
    bool operator()(const T &left, const T& right) const { 
    return left.x == right.x; 
    } 
}; 

int main() { 
    typedef std::unordered_map<foo<int>, int, foo_hasher<foo<int>>, foo_equality<foo<int>>> Map; 
    Map mp; 
    foo<int> x(5); 
    mp[x] = 10; 
    mp[foo<int>(10)] = 22; 

    std::for_each(mp.begin(), mp.end(), [](const Map::value_type &val) { 
    std::cout << val.first.x << ", " << val.second << "\n"; 
    }); 
} 

注意。

関連する問題