I’m creating a std::map
using keys that contain e.g. double
s as identifiers. However, I need the keys to have some leeway, i.e. tolerance, to identify a key as “the same”.
I’ve successfully managed to implement that by defining the operators <
and ==
myself.
I’m now in the following situation: Say I add an element to my map using some key a
. I can now retrieve the values stored with that key using some key b
, whose identifying double is slightly off from a
‘s. That’s all as intended. However, what I want now is to compare the difference between the keys a
and b
. To do so, I’m looking for a way to retrieve a
from the map.
Is there any way of doing so without iterating over the entire map to find the first element that passes a == b
?
Here’s example code of what I’m trying to do:
#include <iostream>
#include <map>
class myKey {
public:
myKey(double x, double tolerance=0.5);
double getX() const;
bool operator<(const myKey& rhs) const;
bool operator==(const myKey& rhs) const;
private:
double _x;
double _tolerance;
};
myKey::myKey(double x, double tolerance){
_x = x;
_tolerance = tolerance;
}
double myKey::getX() const {
return _x;
}
bool myKey::operator<(const myKey& rhs) const {
return (rhs._x - _x) > _tolerance;
}
bool myKey::operator==(const myKey& rhs) const {
return std::abs(_x - rhs._x) < _tolerance;
}
// --------------------------------------------------
int main() {
std::map<myKey, double> myMap;
// create a key and assign it a value in the map
myKey a = myKey(1.234, 0.5);
double aval = 3.14159;
myMap[a] = aval;
double value_of_a_in_map = myMap[a];
std::cout << "Checking myMap[a]: ";
std::cout << "same value? " <<
(aval == value_of_a_in_map) << std::endl;
// Get a new key that should pass a == b
// since it's within the tolerance of 0.5
myKey b = myKey(1.345, 0.5);
std::cout << "a == b? " << (a == b) << std::endl;
// retrieve value of `a` from map using `b`
double value_of_a_in_map_using_b = myMap[b];
std::cout << "Checking myMap[b]: ";
std::cout << "same value? " <<
(aval == value_of_a_in_map_using_b) << std::endl;
// How do I get original value(s) of `myKey a` from the map?
// Can I do it without iterating over the entire map?
// This works
for (auto entry: myMap){
myKey mapKey = entry.first;
if (mapKey == b) {
std::cout << "Found a ! x= " << mapKey.getX() << std::endl;
}
}
return 0;
}
1