C++正确地使用std::set和对象
C++ use std::set with objects properly
我正在尝试将Nodes
存储在std::set
中,这样当我使用set::find
方法时,如果它们的状态相同,它会告诉我Node
在集合中。我是否需要以某种方式比较operator==
和compare
中的其他Node
属性?
你能帮我吗?
这是代码:
#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!";
}
}
由您决定有多少对象应该充当集合的"键",并相应地编写比较器。如果您只想让集合查看state
矩阵,并在匹配的情况下将两个节点视为等效节点,那么您的比较器就可以了。
请注意,您只需要compare
函子就可以与集合一起使用。它不将对象与operator==
进行比较,所以只有在有其他用途的情况下才需要。
不,您只需要能够比较状态。
相关文章:
- std::set 是否将对象连续存储在内存中?
- 我可以制作一个std::set的constexpr对象吗
- std::set 不会检测到重复的自定义对象
- 如何从对象的指针清空 std::set?
- 如何实例化多个 set 对象来测试 Set 类的各种构造函数和方法
- C++ 在 std::set 的嵌套对中搜索对象
- 函数对象无法识别它获得的参数(std::set<int>)
- 存储对std::set对象的引用/指针
- 如何在 std::set 中存储指向对象的指针(或引用)
- 如何从对象中调用我的set回调函数
- 带有对象的段错误set_union:std::set<CardSet>
- 在 std::set 上按名称查找对象
- 在 std::set 中查找对象时出错
- 无法访问 std::set 中对象的非常量成员函数C++
- C++类和对象使用set方法获得用户输入
- C++正确地使用std::set和对象
- 如何使 set:: find() 适用于自定义类对象
- 在std::set/std::map中存储具有多个不同类型字段的c++对象的有效方法
- 通过迭代器返回set对象的地址
- C++使用set函数更新对象属性