我試圖將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!";
}
}
在添加到集合後,節點的狀態是否改變?一套預計它的元素保持穩定,以便它們總是以相同的方式比較。 – 2014-11-03 15:01:45
@ScottLangham不,他們總是一樣的。 – mariya 2014-11-03 15:03:26
您是否知道在一個集合中存儲兩個相同(具有相同狀態)的元素(您的案例中的節點)是不可能的。 – 2014-11-03 15:07:02