Can anyone explain the output I am getting from this simple program using std::map
. Note that I insert p
into the map, but not q
yet it says it found them both, but also says there is only 1 element in the map!
#include <map>
#include <iostream>
struct screenPoint {
float x = 0, y = 0;
screenPoint(float x_, float y_): x{x_}, y{y_}{}
};
bool operator<(const screenPoint& left, const screenPoint& right){
return left.x<right.x&&left.y<right.y;
}
std::map<screenPoint, float> positions;
int main(int argc, const char * argv[]) {
auto p = screenPoint(1,2);
auto q = screenPoint(2,1);
positions.emplace(p,3);
auto f = positions.find(p);
auto g = positions.find(q);
if (f == positions.end()){
std::cout << "f not found";
} else {
std::cout << "f found";
}
std::cout << std::endl;
if (g == positions.end()){
std::cout << "g not found";
} else {
std::cout << "g found";
}
std::cout << std::endl;
std::cout << "number elements: " << positions.size() << "\n";
return 0;
}
Output:
f found
g found
number elements: 1
The problem is with the way you defined the comparison functor, in this case. The two elements, p
, and q
, have the same x
and y
, just inverted.
Your logic checks that the x
of one is less than that of the other, as well as the y
s. This can never evaluate to true
, for these inputs.
Try this snippet:
int main()
{
auto p = screenPoint(1,2);
auto q = screenPoint(2,1);
std::cout << std::boolalpha << (p < q) << " " << (q < p) << std::endl;
}
It will print out
false false
So p
is not less than q
, and q
is not less than p
. As far as the map is concerned, that makes them equivalent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With