C++:带有坐标的矢量.如何删除重复项以及它们之间的所有元素
C++: Vector with coordinates. How to remove duplicates and all elements that lie between them
我有一个带有坐标的向量。我要做的是查找是否存在重复项并删除它们之间的所有元素。矢量包含这些坐标。(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;
}
相关文章:
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 使用折叠表达式打印每个元素之间的空格
- 如何计算大小为 1000 x 1000 的 2D 数组中 2 个元素之间的步幅?C++
- OpenCV 文件存储 - 错误:元素之间的解析错误 (icvYMLParseValue) 缺失
- C++ - 前两个元素之间的差异
- 字符串和向量<string>元素之间的区别
- 当我删除数组时,指针在哪里?指向数组的指针与数组中的元素之间的区别
- 在给定某些约束的情况下,求出元素之间的最大距离
- 矢量<unique_ptr>元素之间的指针<myclass>
- 一种按排序顺序保持元素的数据结构,支持快速插入和计算连续元素之间的最大差异
- OpenGL:在两个元素之间画一条线
- 元素之间的输出逗号
- 是否保证 std::vector 不会在元素之间留下间隙
- 为什么我的程序是,数组中任意两个元素之间的最小差异,给出相反的结果
- 使用boost multiarray迭代器在数组元素之间进行赋值
- googletest匹配器,用于检查容器元素之间的关系
- C++数据结构,用于存储两组唯一元素之间的多个关系
- 为在unordered_set中查找指定元素之间的相等性
- 如何在两个容器的元素之间执行成对二进制操作?
- 如何获得两个std::set的元素之间的差异<string>?