比较复杂的结构

Comparing a complex structure

在过去的 2 个小时里,我一直在努力解决这个问题,通过 SO 和 google 寻找解决方案。我尝试实现运算符 == 和嵌套的 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;
};

一些 int 属性实际上是枚举,但对于问题来说应该无关紧要。 所以基本上,我填充了一个 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

替换 lambda 时,编译给了我一堆关于重载函数或缺少运算符==的错误

也许这样是不可能的,那么我将不得不手动循环遍历两个级别的向量并执行搜索或查看我的数据结构

提前致谢!

最终解决方案:

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());

警告!!: 在推回 multilev 向量中的 Leveli 对象之前,应该对向量深度 (std::vector) 进行排序 (std::sort)。

我能够成功测试所有这些,应该足以让你的程序运行

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.
}