Re: hash_map
aaragon <alejandro.aragon@gmail.com> wrote in message ...
Hello everyone,
I have a VERY BIG set of double values that I want to map to intervals
so I thought a clever way to do this was using a hash table. Let's say
that I want to map all double values in the range 0-0.5 to a single
std::pair<double,double>.
This is what I've done so far:
#include <iostream>
#include <ext/hash_map>
non-standard header. (AFAIK)
#include <boost/functional/hash.hpp>
non-standard header.
using namespace __gnu_cxx;
OUCH!!
using namespace std;
ouch!!
struct eqstr
{
bool operator()(const double& o, const double& p) const
{
return (o == p);
Comparing doubles for equality is most often bad [1]. Compare to a range.
if( ( o + 0.0001 > p ) && ( o - 0.0001 < p ) ){ return true;}
return false;
Output the numbers using a stream with 'fixed' and a big 'precision', and
see if they are (really/almost) equal (in the limited output (rounding
errors in stream output)).
Not sure this is your problem, but, it (==) should be fixed.
}
};
namespace __gnu_cxx{
Are you a GNU systems/compiler developer?
template<> struct hash<double> {
size_t operator()(double __x) const {
boost::hash<double> double_hash;
return double_hash(__x);
}
};
}
void lookup(const hash_map<double, pair<double,double> , hash<double>,
eqstr>& Map, const double number){
hash_map<double, pair<double,double> , hash<double>,
eqstr>::const_iterator it = Map.find(number);
cout << number << ": "
<< (it != Map.end() ? "present" : "not present")
<< endl;
}
int main(){
hash_map<double, pair<double,double> , hash<double>, eqstr> HashMap;
HashMap.insert(make_pair(0.1,make_pair(0.,0.5)));
lookup(HashMap,0.1);
lookup(HashMap,0.05);
}
aaragon@aaragon-laptop:~/Desktop$ ./a.out
0.1: present
0.05: not present
Now, the thing is that I can't map the value of 0.05 to the same pair
because my hashing function doesn't to this. Any ideas???
Thank you,
a^2
[1]
{
std::ostringstream sos;
sos.setf( std::ios_base::fixed, std::ios::floatfield );
sos.precision( 40 );
double num( 0.1 );
sos<<"double num( 0.1 )="<<num<<std::endl;
std::cout<<sos.str()<<std::endl;
}
// out: double num( 0.1 )=0.10000000000000001
--
Bob R
POVrookie