How to map a bool to a 3d point struct with std::map?

后端 未结 6 797
情话喂你
情话喂你 2020-12-10 06:21

How do I use the following struct:

struct point 
{
    int x;
    int y;
    int z;
};

as a key for std::map

6条回答
  •  醉话见心
    2020-12-10 07:04

    Of course, boost::tuple would make this utterly unnecessary.

    Update Adding the all-inclusive have-your-cake-and-eat-it-too no-drawback solution here. IMHO it rocks!

    #include 
    
    struct point 
    {
        int x, y, z;
        point(int x, int y, int z) : x(x), y(y), z(z) {}
        bool operator<(const point& rhs) const 
        {
            return boost::tie(x, y, z) < boost::tie(rhs.x, rhs.y, rhs.z);
        }
    };
    

    Here is the kicker: it all optimizes away. Compile:

    int main()
    {
        point a(1,2,3), b(3,2,1);
        bool lt = a

    With g++ -O2 yields the following in assembly.

    main:
    .LFB1132:
            pushl   %ebp
            xorl    %eax, %eax
            movl    %esp, %ebp
            popl    %ebp
            ret
    .LFE1132:
    

    The compiler was able to optimize the whole of this program to ... return 0 effectively. That is pretty neat.


    Here goes the simple answer:

    struct point 
    {
        point(int x, int y, int z) 
            : x(x), y(y), z(z) {}
        int x;
        int y;
        int z;
        bool operator<(const point& rhs) const 
        {
            if (x

    Also, I would consider looking for a redefinition of my struct that will allow using std::lexicographical_compare

    #include 
    
    // ...
    bool operator<(const point& rhs) const 
    {
        return std::lexicographical_compare(&xyz, &xyz+3, &rhs.xyz, &rhs.xyz+3);
    }
    

提交回复
热议问题