C++正确地使用std::set和对象

C++ use std::set with objects properly

本文关键字:set 对象 std 正确地 C++      更新时间:2023-10-16

我正在尝试将Nodes存储在std::set中,这样当我使用set::find方法时,如果它们的状态相同,它会告诉我Node在集合中。我是否需要以某种方式比较operator==compare中的其他Node属性?

你能帮我吗?

这是代码:

    #include <iostream>
    #include <vector>
    #include <set>
    using namespace std;
    class Node {
        bool operator==(const Node& rhs) const {
            for(int i = 0; i < 3; i++) {
                for(int j = 0; j < 3; j++) {
                    if(this->state[i][j] != rhs.get_block(i,j)) {
                       return false;
                    }
                }
            }
            return true;
         }
         //other methods including constructor
         private:
             int zero_pos[2];//the coordinates of the 0 in the matrix
             int state[3][3];//the matrix with numbers
             int current_path;//the distance from root
             Node* predecessor;//the parent of the Node
     };
    struct compare {
      bool operator()(const Node& f , const Node& s) const{
        vector<int> _f , _s;
        for(int i = 0; i < 3; i++) {
                    for(int j = 0; j < 3; j++) {
                        _f.push_back(f.state[i][j]);
                        _s.push_back(s.state[i][j]);
                    }
                }
        return _f < _s;
      }
    };
    //then I use it like this:
    void main() {
        set<Node , compare> closed;
        Node *node = new Node();
        if(closed.find(*node) != closed.end()) {
            cout<<"Found it!";
        }
    }

由您决定有多少对象应该充当集合的"键",并相应地编写比较器。如果您只想让集合查看state矩阵,并在匹配的情况下将两个节点视为等效节点,那么您的比较器就可以了。

请注意,您只需要compare函子就可以与集合一起使用。它不将对象与operator==进行比较,所以只有在有其他用途的情况下才需要。

不,您只需要能够比较状态。