vendredi 27 mai 2016

Custom class pointer as unordered map key

I'm trying to implement unordered_map with pointer to custom class as key and integer as value.
I thought pointer is just an address, so I wouldn't have to create comparison template for unordered_map, since map would compare between addresses. But I get compile error.
My code is as follow for simple testing. Can anyone help me to fix what have I done wrong?

#include <cstdlib>
#include <unordered_map>
#include <iostream>

using namespace std;

class MyClass{
    public:
        MyClass(int id){m_id = id;};
        void PrintThis(){cout << " This is test " << endl;};
        int m_id;
};


class Test{
    public:
        unordered_map<MyClass* mc, int test> mapTest;

};

int main(){
    MyClass* mc1 = new MyClass(1);
    MyClass* mc2 = new MyClass(2);

    Test* tt1 = new Test();
    tt1->mapTest.insert(make_pair<MyClass*, int>(mc1, 10));
    tt1->mapTest.insert(make_pair<MyClass*, int>(mc2, 20));

    auto search = tt1->find(mc1);
    if(search != tt1->end()) {
        search->first->PrintThis();
    }else{
        cout << "not Found " << endl;
    }

}

Error message is as follow

./main.cpp:17:44: error: wrong number of template arguments (1, should be 5)
         unordered_map<MyClass* mc, int test> mapTest;
                                            ^
In file included from /usr/include/c++/4.8/unordered_map:48:0,
                 from ./main.cpp:2:
/usr/include/c++/4.8/bits/unordered_map.h:97:11: error: provided for 'template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> class std::unordered_map'
     class unordered_map : __check_copy_constructible<_Alloc>
           ^
./main.cpp: In function 'int main()':
./main.cpp:26:18: error: request for member 'insert' in 'tt1->Test::mapTest', which is of non-class type 'int'
     tt1->mapTest.insert(make_pair<MyClass*, int>(mc1, 10));

I think I can manage line 26 error, if line 17 gets fixed...

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire