在集合中查找使用结构C++的元素
Finding an element in a set that uses a struct C++
我正在C++中创建 8 谜题。我根据输入获取拼图,然后创建一个包含拼图的集合。该集合使用结构来保存 x,y 坐标和 id。这是我的结构:
struct tile {
int id;
int xCord;
int yCord;
tile(int a, int b, int c) :
id(a),
xCord(b),
yCord(c) {}
bool operator<(const tile& Rhs) const {
if (xCord < Rhs.xCord)
return true;
else if (xCord > Rhs.xCord)
return false;
else if (xCord == Rhs.xCord) {
if (yCord < Rhs.yCord)
return true;
else if (yCord < Rhs.yCord)
return false;
else
return false;
}
}
void print() const {
cout << "Node - id=" << id << " Coordinates=(" << xCord << "," << yCord << ")" << endl;
}
};
此时,我需要洗牌拼图,这涉及找到 id 为0
的空图块。我不知道如何使用find
函数来设置我的设置。
到目前为止,我已经使用了这个,但是有一个语法错误:
set<tile>::iterator it = puzzleSet.find(0);
这是我的集合声明:
set<tile> puzzleSet;
有人可以帮助我吗?提前谢谢。
你的集合是按坐标排序的,所以你的集合不能帮助你按ID找到。 可能的解决方案:std::find_if(puzzleSet.begin(), puzzleSet.end(), [id](puzzleSet const & item){ return item.id == id; });
如果线性搜索太昂贵。 您可以添加另一个按 ID 排序的集合,或者尝试按 ID 和坐标对集合进行排序(如果适用(
代码中的一个小错别字:
if (yCord < Rhs.yCord)
return true;
else if (yCord < Rhs.yCord) // here should be >
return false;
语法错误是因为set<tile>::find
期望另一个tile
,而不是int
。C++14 添加了允许按另一种类型搜索的新重载,请参阅 ref。该消息来源还说,要启用它们,set
的比较器必须是透明的。默认比较器std::less<tile>
据我所知,没有明确表示是透明的。因此,解决方案是定义自定义比较器:
struct comp
{
public:
using is_transparent = void;//Can be anything, just needs to be defined.
constexpr bool operator()(const tile &lhs, const tile &rhs) const
{
return lhs < rhs;//You should reimplement to create proper ordering.
}
constexpr bool operator()(const tile &lhs, int ID) const
{
return lhs.ID < ID;//You should reimplement to create proper ordering.
}
constexpr bool operator()(int ID, const tile &rhs) const
{
return ID < rhs.ID;//You should reimplement to create proper ordering.
}
};
#include <set>
int main() {
std::string buffer = "a s d f ";
std::cout << "Before " << buffer << std::endl;
std::set<tile, comp> set;
set.find(0);//Should compile and find the tile with zero ID
}
请注意,比较器必须创建相同的弱排序,所有重载才能正常工作。您的operator<
实现不会,因为正如@Alexander在其答案中指出的那样,您的磁贴未按 ID 排序。
编辑:所以不要像现在这样使用comp,你应该改变实现以正确创建排序。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?