简体   繁体   中英

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

I have a struct of CvPoint and int as follows.

struct strcOfPoints {
        CvPoint p;
        int c;
    };

And i have a vector of strcOfPoints like this

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

Q. How can we apply std::sort and std::erase on vector of struct to remove the duplicate points?

Note. I can do it with vector of Points. but i am failed to do it for vector of structure of Point and int.

Need guidelines to process further. Thanks

First, lets build a comparator:

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

Next we sort the vector:

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

Finally we erase any duplicates:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM