如何删除向量的重复坐标

问题描述 投票:2回答:4

我将点的坐标传递到向量中,并且有一些重复点,所以我想删除其他重复点,只保留唯一的点。

例如:

vector<Point2f>  points;

points[0]=Point2f(1,1);
points[1]=Point2f(2,3);
points[2]=Point2f(1,1);
points[3]=Point2f(2,3);
points[4]=Point2f(1,1);
points[5]=Point2f(4,1);

我想得到这样的结果:

points[0]=Point2f(1,1);
points[1]=Point2f(2,3);
points[2]=Point2f(4,1);

PS元素顺序不变。

我尝试过的显示如下:

#include <opencv2/core/core.hpp>

#include <vector>
#include<iostream>

using namespace std;
using namespace cv;

int main()
{
    vector<Point2f>  pointTemp;

    pointTemp[0]=Point2f(1,1);
    pointTemp[1]=Point2f(2,3);
    pointTemp[2]=Point2f(1,1);
    pointTemp[3]=Point2f(2,3);
    pointTemp[4]=Point2f(1,1);
    pointTemp[5]=Point2f(4,1);

    for(vector<Point2f>::iterator it=pointTemp.begin();it!=pointTemp.end();it++)
    {
        for(vector<Point2f>::iterator it1=it+1;it1!=pointTemp.end();)
        {
            if(it->x==it1->x&&it->y==it1->y)
            {
                it1=pointTemp.erase(it1);
            }
            else
            {
                it1++;
            }
        }
    }
    //cout<<pointTemp.size()<<endl;

    return 0;
}
c++ opencv vector point
4个回答
3
投票

这是我的意思。可能需要将--std=c++11作为参数传递给g ++。请注意,将保留唯一元素的插入顺序。对于运行时复杂度,它也是O(N)


2
投票

这可以通过首先对点进行排序(使用std :: sort),然后消除重复的点(使用std :: unique)来完成。为此,您将需要一个功能compare()


0
投票
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

struct Point2f
{
    float x;
    float y;
};

int main(int argc, char const *argv[])
{
    std::vector<Point2f> points =
    {
        {1, 1}, {2, 3}, {1, 1}, {2, 3}, {1, 1}, {4, 1}
    };

    auto print = [&]()
    {
        for (const auto &point : points)
        {
            std::cout << "(" << point.x << " " << point.y << ") ";
        }
        std::cout << std::endl;
    };

    // first sort
    std::sort(points.begin(), points.end(), [](const Point2f & lhs, const Point2f & rhs)
    {
        return lhs.x < rhs.x && lhs.y < rhs.y;
    });

    // print
    print();

    // remove duplicated element
    auto it = std::unique(points.begin(), points.end(), [](const Point2f & lhs, const Point2f & rhs)
    {
        return lhs.x == rhs.x && lhs.y == rhs.y;
    });
    points.resize(std::distance(points.begin(), it));

    // print
    print();

    return 0;
}

0
投票

请注意equal function。如果我们打算剔除similar足够的点,则应使用为similar点赋予相同散列值的散列,以及将approximate-equal分组为相同的similar points。就我而言,我使用以下代码:

© www.soinside.com 2019 - 2024. All rights reserved.