What is this use of std::map doing?

后端 未结 2 653
孤街浪徒
孤街浪徒 2021-01-19 02:09

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 i

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 02:43

    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 ys. 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.

提交回复
热议问题