I meant to implement a two dimensional hash map using std::map with c++ STL.
First of all, a data class was defined.
class DInfo {
public:
int i, j, k;
DInfo(int _i, int _j, int _k) { i=_i; j=_j; k=_k; }
};
Simple, enough. Now, it's time to define a two dimensional hashmap.
typedef std::map DMAP;
std::map diMap;
No problem is observed till here. Let's write some codes to use them.
There're some RogueWave stuff starting with "RW" for DB interface but just ignore that part.
RWDBTable tbl=database.table("MyTable");
RWDBSelector sel=database.selector();
sel << tbl["Field1"] << tbl["Field2"] << tbl["Field3"];
RWDBReader rdr = sel.reader(conn);
while (rdr()) {
int i, j;
rdr >> i >> j;
DMAP dmap=diMap[i];
DInfo di(i, j, k);
dmap[j]=di;
diMap[i]=dmap;
}
Everything looks fine. Let's compile it using gcc. Ooops!
testSDDI.cpp:48: error: no matching function for call to `DInfo::DInfo()'
DInfo.h:4: note: candidates are: DInfo::DInfo(const DInfo&)
DInfo.h:13: note: DInfo::DInfo(int, int, int)
Huh!!!??? What happens here?
I spent couple of hours to find out the problem of my code and found, finally.
It's missing default constructor of the class DInfo. Let's add the default constructor.
class DInfo {
public:
int i, j, k;
DInfo(int _i, int _j, int _k) { i=_i; j=_j; k=_k; }
DInfo() { i=j=k=0; };
};
In the following line above
...
dmap[j]=di;
...
The default constructor of DInfo is called to instantiate an object for the element of dmap[j] seemlessly
and it calls copy constructor to copy(overwrite) it the contents of di.
Thus we still need default constructor although no actual code calls it.
Now, it's compiled smoothly. Yahoo!
Remember, we'd better implement a default constructor for a class while we're using some library
without knowing the detail of it.
Hi, vio!
I'm so glad to talk with you on programming over Internet even though you are far far away!
Actually, map::operator[]() creates an element with the default constructor before copy assignment happens if the element does not exists but map::insert() doesn't.
dmap.insert(make_pair(j, DInfo(i,j,k))) will have same effect with the constructor to dmap[j] = DInfo(i,j,k)
Looking forward to seeing another your C++ article! ^___^
insert() seems like useful and straightforward in this case.
Honestly, I wasn't familiar with C++ hash map.
Thank you for your tip.
Post preview:
Close preview