我试图将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