没有主题解决我在 C++ 中比较结构作为键映射的问题。
结构体代码如下:
struct XYZ{
int x, y, z;
}
struct XYZComp{
bool operator()(const XYZ& l, const XYZ& r)
{
return ((l.x==r.x)&&(l.y==r.y)&&(l.z==r.z));
}
}
Run Code Online (Sandbox Code Playgroud)
主要看起来像
int main()
{
map<XYZ, int, XYZComp> m;
m.insert(std::make_pair<XYZ,int>({1,2,3}, 1)); //ok
map<XYZ, int, XYZComp>::iterator it = m.find({1,0,3});
if(it!=m.end())
{
std::cout<<"Key exists in map";
}
else
{
m.insert(std::make_pair<XYZ,int>({1,0,3}, 1));
//never come here
//compiler thinks key already exists in map
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我只是在没有 XYZComparer 的情况下尝试过,但它仍然不起作用。
struct XYZ{
int x,y,z;
bool operator==(const XYZ& xyz)
{
return (x=xyz.x) && (y=xyz.y) && (z=xyz.z);
}
bool operator<(const XYZ& xyz)
{
return (x>xyz.x) && (y>xyz.y) && (z>xyz.z);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试地图中的现有项目时,如何解决比较这些结构 XYZ 的问题。
编辑:当至少一个数字正确时,编译器认为结构是相同的。
用于std::map
订购<
商品。因此,您struct XYZComp
需要提供用户定义的operator <
.
一个非常简单的解决方案是使用std::tie:
#include <tuple>
//..
struct XYZComp
{
int x,y,z;
bool operator < (const XYZComp& xyz) const
{
return std::tie(x, y, z) < std::tie(xyz.x, xyz.y, xyz.z);
}
//...
};
Run Code Online (Sandbox Code Playgroud)
std::tie
为结构体的元素引入了字典顺序。
您可以通过级联 < 比较来完成相同的操作,但代码会变得更长并且更容易出错:
struct XYZComp
{
int x,y,z;
bool operator < (const XYZComp& xyz) const
{
if ( x < xyz.x )
return true;
if ( x == xyz.x && y < xyz.y )
return true;
if ( x == xyz.x && y == xyz.y )
return z < xyz.z;
return false;
}
//...
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5184 次 |
最近记录: |