c++ - map keys of abstract classes that are logically similar -
suppose user uses library kbase
vbase
classes. user adds pairs of keys , values of classes available him (he implemented them using library) - v
, k
. in library, when added, want keys logically similar (have same string) "merged" single key.
he're code sample i've tried :
//---------------------------library.h------------------------// #include <map> #include <vector> #include <iostream> using namespace std; map<kbase*,vector<vbase*>> mapa; void printmap(); void addtomap(kbase* k1, vbase* v2); class kbase { public: virtual ~kbase(){} }; class vbase { public: virtual ~vbase(){} }; //---------------------------library.cpp------------------------// void printmap() { // expect 3 keys implemented. (auto : mapa) cout << i.first << endl; } void addtomap(kbase* k1, vbase* v2) { // create k1. if doesnt exist - vector created. // otherwise, object obtained. mapa[k1]; mapa[k1].push_back(v2); } //------------------------user----------------------------// #include "library.h" // user's implementation. class k : public kbase { public: k(string inputstring) { kstring = inputstring; } ~k(){} string kstring; }; class v : public vbase { public: v(string inputstring) { vstring = inputstring; } ~v(){} string vstring; }; int main() { // user adds keys , values addtomap(new k("key1"), new v("value1")); addtomap(new k("key1"), new v("value2")); addtomap(new k("key1"), new v("value3")); addtomap(new k("key2"), new v("value4")); addtomap(new k("key2"), new v("value5")); addtomap(new k("key2"), new v("value6")); addtomap(new k("key3"), new v("value7")); addtomap(new k("key3"), new v("value8")); addtomap(new k("key3"), new v("value9")); printmap(); return 0; }
obviously, cant add base class key directly. , library not aware of classes implemented user (that inherit classes of library). again, how can library know if objects given logically similar.
should use different data structure purpose?
c++ map uses equivalence concept finding entry, defined via “less” comparison. 2 keys k1 , k2 considered equivalent if k1 “is not less than” k2
, k2 “is not less than” k1
. need define functor comparing pointers kbase
class.
class kbaselesscompare { public: bool operator() (const kbase * k1, const kbase * k2) { // following, shall define comparison return k1->name < k2->name; } }
then change map definition following:
map<const kbase*, vector<vbase*>, kbaselesscomapre> mapa;
Comments
Post a Comment