C++:带有坐标的矢量.如何删除重复项以及它们之间的所有元素

C++: Vector with coordinates. How to remove duplicates and all elements that lie between them

本文关键字:元素 之间 坐标 C++ 何删除 删除      更新时间:2023-10-16

我有一个带有坐标的向量。我要做的是查找是否存在重复项并删除它们之间的所有元素。矢量包含这些坐标。(0,0)(0,1)(0,0)(0,-1)(0,-2)我需要做的是检查第一个元素并找到任何重复项,然后删除它们之间的所有元素以及重复项。在这种情况下,输出将是(0,0)(0,-1)(0,-2)

这是我的结构以及我如何将它们放入向量中。

struct Coordinate
{
 public:
 int x;
 int y;
 Coordinate(int valuex, int valuey) : x(valuex), y(valuey) {}
};
vector<Coordinate> coords;
coords.push_back(Coordinate(x, y));

任何提示或方向将不胜感激。

也许是这样的东西?活生生的例子:http://ideone.com/IHLg3t

#include <iostream>
#include <vector>
#include <algorithm>
#include <ostream>
struct Coordinate
{
    public:
        int x;
        int y;
        Coordinate(int valuex, int valuey) : x(valuex), y(valuey) {}
};
bool sortcomp(const Coordinate &a, const Coordinate &b)
{
    return (a.x < b.x) || (a.y < b.y);
}
bool compare(const Coordinate &a, const Coordinate &b)
{
    return (a.x == b.x) && (a.y == b.y);
}
std::ostream& operator << (std::ostream& os, const std::vector<Coordinate> &v)
{
    for (auto it = v.begin(); it != v.end() - 1; ++it)
        std::cout<<"("<<it->x<<", "<<it->y<<"), ";
    std::cout<<"("<<v[v.size() - 1].x<<", "<<v[v.size() - 1].y<<")";
}
int main()
{
    std::vector<Coordinate> v = {{0,0}, {0,1}, {0,0}, {0,-1}, {0,0}, {1,0}};
    std::sort(v.begin() + 1, v.end(), sortcomp);
    v.erase(std::unique(v.begin() + 1, v.end(), compare), v.end());
    if (v.size() > 2)
    {
        for (unsigned i = 1; i < v.size() - 1; ++i)
        {
            v.erase(v.begin() + i);
            i = 0;
        }
    }
    std::cout<<v;
}