2014-11-03 129 views
0

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

你能帮我吗?

下面是代码:

#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!"; 
     } 
    } 
+0

在添加到集合后,节点的状态是否改变?一套预计它的元素保持稳定,以便它们总是以相同的方式比较。 – 2014-11-03 15:01:45

+0

@ScottLangham不,他们总是一样的。 – mariya 2014-11-03 15:03:26

+0

您是否知道在一个集合中存储两个相同(具有相同状态)的元素(您的案例中的节点)是不可能的。 – 2014-11-03 15:07:02

回答

1

没有,你只需要能够比较的状态。

2

您可以决定该对象的多少作为集合的“关键”,并相应地编写您的比较器。如果你只希望集合看看state矩阵,并且如果两个节点相同,那么你的比较器就没问题。

请注意,您只需要compare仿函数用于该集合。它不会将对象与operator==进行比较,所以如果您有其他用途,您只需要这样做。