c++ - Mapping vector pointers of different type -
assuming want have vectors each contain objects of different type, there way map pointers them ? this:
std::vector<class1> vec1; std::vector<class2> vec2; std::vector<class3> vec3; mapper.addvectorptr(&vec1); mapper.addvectorptr(&vec2); mapper.addvectorptr(&vec3); std::vector<class1> * ptr1 = mapper.getvectorptr<class1>; std::vector<class2> * ptr2 = mapper.getvectorptr<class2>; std::vector<class3> * ptr3 = mapper.getvectorptr<class3>; i utilize custom class vector pointer member, derive mutual base of operations class. coudld downcast them desired class , retrieve pointer to see if there improve options.
you should checkout http://www.cplusplus.com/reference/typeinfo/type_info/ . can typeinfo way. allowing create map integer (=the hashcode) key.
you can implement mapclass follows (requires constructor without arguments)
#include <vector> #include <typeinfo> #include <map> #include <iostream> class typemap{ std::map<unsigned long, void*> m_ptrs; public: template<typename a> void addvectorptr(std::vector<a>* b){ a; m_ptrs[ typeid(a).hash_code() ] = b; } template<typename a> std::vector<a>* getvectorptr(){ a;//this why need default constructor homecoming (std::vector<a>*) (m_ptrs[ typeid(a).hash_code() ]); } }; int main(){ std::vector<int>* t1 = new std::vector<int>(3,3); typemap tm; tm.addvectorptr(t1); std::vector<int> v=*(tm.getvectorptr<int>()); for(auto = v.begin(); it!= v.end(); ++it){ std::cout<<*it<<std::endl; } } c++ mapping stdvector
No comments:
Post a Comment