我正在尝试将Nodes
存储在std::set
中,这样当我使用set::find
方法时,它会告诉我Node
是否在集合中国家是一样的。我是否需要以某种方式比较Node
和operator==
中的其他compare
属性?
你能帮助我吗?
以下是代码:
#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 :(得分:2)
由您来决定该对象应该作为该组的“键”的多少,并相应地编写您的比较器。如果您只希望该集合查看state
矩阵,并将两个节点视为等效,那么您的比较器就可以了。
请注意,您只需要使用compare
仿函数来使用该集。它不会将对象与operator==
进行比较,所以如果您有其他用途,则只需要它。
答案 1 :(得分:1)
不,你只需要能够比较状态。