C++ set 使用自定义结构体做Key值 ,已经重载“<”号,但是在进行并集运算时报错

qq_41993451 2018-07-21 12:03:43
struct MyCOORD
{
short X;
short Y;
bool operator == (const MyCOORD &crd) const
{
if (this->X == crd.X && this->Y == crd.Y)
{
return true;
}
return false;
}

bool operator != (const MyCOORD &crd) const
{
return !(*this == crd);
}

bool operator < (const MyCOORD &crd) const
{
if (crd == *this)
{
return false;
}
return this->Y < crd.Y || this->X < crd.X;

}
bool operator > (const MyCOORD &crd) const
{
return !(*this < crd);
}

};

int main() {

set<MyCOORD> test;
test.insert({ 2,2 });
test.insert({ 1,3 });
test.insert({ -1,2 });
test.insert({ 2,2 });
test.insert({ 2,2 });
test.insert({ 2,2 });

set<MyCOORD> test2;
test2.insert({ 1,2 });
test2.insert({ 2,3 });
test2.insert({ -2,2 });
test2.insert({ 2,2 });
test2.insert({ 3,2 });
test2.insert({ 1,2 });

set<MyCOORD> result;

set_intersection(test.begin(),test.end(), test2.begin(),test2.end(),result.begin());

system("pause");
return 0;
}


报错信息:error C2678: 二进制“=”: 没有找到接受“const MyCOORD”类型的左操作数的运算符(或没有可接受的转换)

另外在使用sort排序时也报错
sort(test.begin(), test.end(), [](MyCOORD first, MyCOORD second) {return first < second; });
错误信息: 未能从“const std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>,std::_Iterator_base0>”为“const std::move_iterator<_RanIt> &”推导 模板 参数
...全文
357 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_41993451 2018-07-21
  • 打赏
  • 举报
回复
重载“<”号修改代码:
bool operator < (const MyCOORD &crd) const
{
if (this->Y < crd.Y)
{
return true;
}
else if (this->Y == crd.Y &&this->X < crd.X)
{
return true;
}
return false;

}


但还是一样的问题,求教
冷风1023 2018-07-21
  • 打赏
  • 举报
回复
set_intersection(test.begin(),test.end(), test2.begin(),test2.end(),inserter(result,result.begin()));

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧