在集合中查找使用结构C++的元素

Finding an element in a set that uses a struct C++

本文关键字:结构 C++ 元素 集合 查找      更新时间:2023-10-16

我正在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,你应该改变实现以正确创建排序。