如何在 CvPoint 和 int 的结构上应用 std::sort 和 std::erase

How to apply std::sort and std::erase on struct of CvPoint and int?

本文关键字:std 应用 结构上 sort erase CvPoint int      更新时间:2023-10-16

我有一个 CvPoint 和 int 的结构,如下所示。

struct strcOfPoints {
        CvPoint p;
        int c;
    };

我有一个像这样的 strcOfPoint 向量

UniquePoints::strcOfPoints s1, s2, s3, s4, s5, s6, s7;
    s1.p = { 33, 122 }, s1.c = 255;
    s2.p = { 68, 207 }, s2.c = 158;
    s3.p = { 162, 42 }, s3.c = 120;
    s4.p = { 219, 42 }, s4.c = 50;
    s5.p = { 162, 216 }, s5.c = 20;
    s6.p = { 162, 216 }, s6.c = 20;
    s7.p = { 162, 216 }, s7.c = 20;
    vector <UniquePoints::strcOfPoints> strpts = { s1, s2, s3, s4, s5, s6, s7 };

问:我们如何在结构的向量上应用 std::sort 和 std::erase 来删除重复的点?

注意。我可以用点向量来做到这一点。但是对于点和整数的结构向量,我未能做到这一点。

需要进一步处理的指南。谢谢

首先,让我们构建一个比较器:

bool compare(strcOfPoints const & lhs, strcOfPoints const & rhs) {
    return std::tie(lhs.p, lhs.c) < std::tie(rhs.p, rhs.c);
}

接下来我们对向量进行排序:

vector<strcOfPoints> strpts = { s1, s2, s3, s4, s5, s6, s7 };
std::sort(strpts.begin(), strpts.end(), compare);

最后,我们删除任何重复项:

strpts.erase(
    std::unique(strpts.begin(), strpts.end(), compare),
    strpts.end());