trouble inserting a struct into a set C++

后端 未结 3 2060
南方客
南方客 2021-01-16 23:49

I am working on an A* pathfinding algorithm, but am having trouble with an error I receive when i insert a struct called node into a set. The error reads: \"Error 1 erro

相关标签:
3条回答
  • 2021-01-16 23:49

    You need to create operator<or specialize std::less for your struct. Another solution could be to use std::array:

    struct node : std::array<5,int> {
        int &f() { return data()[0]; }
        int &g() { return data()[1]; }
        int &h() { return data()[2]; }
        int &x() { return data()[3]; }
        int &y() { return data()[4]; }
    };
    

    and you will inherit operator< from it. Another benefit - you can access underlying data as array, which would simplify serializing etc.

    0 讨论(0)
  • 2021-01-16 23:51

    As you may know if you've familiarized yourself with the documentation of std::set, it is an ordered container. Therefore there must be a way to compare the elements of the set so that they can be ordered. From the documentation, we know that the default comparison functor of std::set is std::less<T>.

    Further, as you may know, std::less<T> does:

    Unless specialized, invokes operator< on type T.

    Since std::less isn't specialized for node, it uses operator<.

    The error message tells you that an overload for operator< does not exist that would have const node (or anything that a node could be converted to) as the left operand.

    The solution is to define such overload.

    0 讨论(0)
  • 2021-01-17 00:07

    std::set is an ordered container so it needs operator< to compare and order elements, allowing fast search. If you don't need this you can use list or vector.

    0 讨论(0)
提交回复
热议问题