Re: How should unordered_map be used correctly ... ?
OK. It is clearer. But like i understand unordered_map is only weakly
sorted by hash. Hash causes some sort of "buckets" of same order in
map. In buckets the equality is decided by your "setequal".
Ah thank you ... I guessed that already through your previous answer
so decided that maybe things would be easier for all of us ;-) if i
was actually finished my code ha ha ha... so here it is... it seems to
work. Let me know if you see anything that I am doing wrong (I mean I
know I use struct and all that which is not for the C++ purist but I
am just prototyping here to understand how unordered_map works. Thx a
lot for your feedbacks.
Thx =D6=F6 Tiib (not sure how to pronounce your name ;-)
-c
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <tr1/unordered_map>
//using namespace stdext;
//http://stackoverflow.com/questions/2099540/defining-custom-hash-
function-and-equality-function-for-unordered-map
template<typename T>
struct point {
T x, y, z;
};
struct hashfunc {
size_t operator() (const point<int> &pt) const { return 541 * pt.x
+ 79 * pt.y + 31 * pt.z; }
};
struct setequal {
bool operator() (const point<int> &pa, const point<int> &pb) const
{ return (pa.x == pb.x && pa.y == pb.y && pa.z == pb.z); }
};
typedef struct voxel {
float data;
};
typedef std::tr1::unordered_map<point<int>, voxel *, hashfunc,
setequal> tablegrid;
float signedrand() { return (drand48()-0.5)*2; }
int main (int argc, const char * argv[])
{
int dim = 1;
float cellsize = 0.01;
//int gridsize = dim * dim * dim;
//printf("grid size %d\n", gridsize);
int npts = 1e6;
tablegrid grid;
point<int> pt;
for (int i = 0; i < npts; ++i) {
if (i%512==0) fprintf(stderr, "\b\b\b\b%d%c", int(100*i/
float(npts-1)), '%');
pt.x = int(dim * signedrand() / cellsize);
pt.y = int(dim * signedrand() / cellsize);
pt.z = int(dim * signedrand() / cellsize);
tablegrid::const_iterator it = grid.find(pt);
if (it != grid.end()) {
// do nothing
}
else {
grid[pt] = new voxel;
}
//printf("val %d\n", hashfunc(pt));
}
printf("\nsize of table %d\n", grid.size());
// delete mem
tablegrid::const_iterator it = grid.begin();
for (; it != grid.end(); ++it) {
delete it->second;
}
printf("delete mem done\n", grid.size());
return 0;
}