我正在用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;
有人可以帮我吗?预先感谢。
答案 0 :(得分:1)
您的集合按坐标排序,因此您的集合无法帮助您按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;
答案 1 :(得分:1)
语法错误是因为set<tile>::find
需要另一个tile
,而不是int
。 C ++ 14添加了新的重载,允许按另一种类型进行搜索,请参见ref。该消息人士还说,要启用它们,set
的比较器必须是 transparent 。默认比较器为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,您应该更改实现以正确创建顺序。