2014-11-03 131 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==進行比較,所以如果您有其他用途,您只需要這樣做。