比较一个复杂的结构
问题描述:
在过去的2个小时里,我一直在嘲弄我的头,通过SO和谷歌寻找解决方案。我试着实施运营商==
和嵌套lambda。比较一个复杂的结构
这里是结构(多重嵌套结构):
struct Deepest{
int att1;
int att2;
};
struct Useless{
int u1;
int u2;
};
struct Leveli {
std::vector<Deepest> deeps;
Useless extra;
};
struct Top{
std::vector<Leveli> multilev;
int cost;
};
一些诠释属性实际上是枚举,但它不应该的问题的问题。所以基本上,我有一个Top对象填充,并且一旦填充,我想识别并消除任何重复的Leveli,仅基于Deepest的向量(我不想比较无用的额外)。下面是我试图让工作代码:
auto sub_comp = [](const Deepest& lhs, const Deepest& rhs) {return (lhs.att1== rhs.att1&& lhs.att2== rhs.att2); };
auto comp = [&](const Leveli& lhs, const Leveli& rhs) {return std::equal(lhs.deeps.begin(), lhs.deeps.end(), rhs.deeps.begin(), sub_comp); };
std::sort(mytop.multilev.begin(), mytop.multilev.end());
auto last = std::unique(mytop.multilev.begin(), mytop.multilev.end(), comp);
mytop.multilev.erase(last, mytop.multilev.end());
编译给了我一个关于重载函数或丢失的运算符一堆错误的==与LHS == RHS更换拉姆达时
也许是不可能这样,那么我将不得不在两个级别的向量上手动循环,并执行搜索或查看我的数据结构
在此先感谢!
最终解决方案:
struct Deepest{
int att1;
int att2;
bool operator==(const Deepest& rhs) {
return att1 == rhs.att1 && att2 == rhs.att2;
}
bool operator<(const Deepest& rhs) {
return att1 < rhs.att1;
}
};
struct Useless{
int u1;
int u2;
};
struct Leveli {
std::vector<Deepest> deeps;
Useless extra;
bool operator==(const Leveli& rhs) {
return std::equal(deeps.begin(), deeps.end(), rhs.deeps.begin());
}
bool operator<(const Leveli& rhs) {
return deeps.size() < rhs.deeps.size();
}
};
struct Top{
std::vector<Leveli> multilev;
};
测试用:
std::sort(strategy.rules.begin(), strategy.rules.end());
auto last = std::unique(strategy.rules.begin(), strategy.rules.end());
strategy.rules.erase(last, strategy.rules.end());
警告!!: 矢量深处(标准::向量)应推回之前进行排序(的std ::排序)多重矢量中的Leveli对象。
答
我是能够成功地测试所有这些,它应该是足以让你的工作方案
struct Deepest {
int att1;
int att2;
};
bool operator==(const Deepest& lhs, const Deepest& rhs) {
return lhs.att1 == rhs.att1 && lhs.att2 == rhs.att2;
}
struct Useless {
int u1;
int u2;
};
struct Leveli {
std::vector<Deepest> deeps;
Useless extra;
};
bool operator==(const Leveli& lhs, const Leveli& rhs) {
return std::equal(lhs.deeps.begin(), lhs.deeps.end(), rhs.deeps.begin());
}
bool operator<(const Leveli& lhs, const Leveli& rhs) {
// You need to implement operator< for your sort to work.
}
另外,在这种情况下,我宁愿使用操作符重载了自定义谓词。您的课程/结构将立即开始工作! –
谢谢!让我真的很亲密,我错过了运营商
我已经用我的最终解决方案更新了我的问题:) –