我有一个向量,其中包含元素的标识符以及x和Y坐标。我想要做的是检查它们是否具有相同的x和y坐标? - 如果他们删除其中一个(基于另一个字段)。查找向量中的重复元素
但是,我在Google上找到了关于“唯一”功能的信息,但是,因为所有的标识符都是唯一的,所以这不起作用?正确?
我在想通过向量比较使用嵌套for循环中的每个项目,有没有更好的方法?
感谢 Ĵ
我有一个向量,其中包含元素的标识符以及x和Y坐标。我想要做的是检查它们是否具有相同的x和y坐标? - 如果他们删除其中一个(基于另一个字段)。查找向量中的重复元素
但是,我在Google上找到了关于“唯一”功能的信息,但是,因为所有的标识符都是唯一的,所以这不起作用?正确?
我在想通过向量比较使用嵌套for循环中的每个项目,有没有更好的方法?
感谢 Ĵ
我刚刚写了一些例子。我希望它有帮助。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
// Sample coordinate class
class P {
public:
int x;
int y;
P() : x(0), y(0) {}
P(int i, int j) : x(i), y(j) {}
};
// Just for printing out
std::ostream& operator<<(ostream& o, const P& p) {
cout << p.x << " " << p.y << endl;
return o;
}
// Tells us if one P is less than the other
bool less_comp(const P& p1, const P& p2) {
if(p1.x > p2.x)
return false;
if(p1.x < p2.x)
return true;
// x's are equal if we reach here.
if(p1.y > p2.y)
return false;
if(p1.y < p2.y)
return true;
// both coordinates equal if we reach here.
return false;
}
// Self explanatory
bool equal_comp(const P& p1, const P& p2) {
if(p1.x == p2.x && p1.y == p2.y)
return true;
return false;
}
int main()
{
vector<P> v;
v.push_back(P(1,2));
v.push_back(P(1,3));
v.push_back(P(1,2));
v.push_back(P(1,4));
// Sort the vector. Need for std::unique to work.
std::sort(v.begin(), v.end(), less_comp);
// Collect all the unique values to the front.
std::vector<P>::iterator it;
it = std::unique(v.begin(), v.end(), equal_comp);
// Resize the vector. Some elements might have been pushed to the end.
v.resize(std::distance(v.begin(),it));
// Print out.
std::copy(v.begin(), v.end(), ostream_iterator<P>(cout, "\n"));
}
是的好!这应该表现良好。 – 2013-04-21 16:26:07
你可以使用std::unique丢弃重复。但是,这不允许您对删除的元素执行任何操作。他们只是从容器中扔掉。当你需要这样做时,你可以使用这种方法:
使用vector.sort与自定义比较函数比较x和y坐标。然后迭代该向量一次,将每个元素与前一个元素进行比较。
当你不想改变向量的顺序,你也可以遍历从开始到结束的向量,每个元素比较具有较高索引的所有元素:
for (int i = 0; i < vector.size(); i++) {
Position current = vector.at(i);
for (int j = i+1; j < vector.size(); j++) {
if current.isEqualPosition(vector.at(j)) {
// found a duplicate
}
}
}
由方式:根据您的具体要求,处理2d空间中对象的更好方法可以是像two-dimensional tree这样的自定义数据结构。
Hm这有复杂性O(N^2) – 2013-04-21 16:22:26
@ hr_117 Named的解决方案也是如此。你认为std :: sort和std :: unique是魔法吗? – Philipp 2013-04-22 05:57:54
不,我真的不认为这会是神奇的。 ;-)但排序应该是O(N * logN),并且希望只有O(N)。 – 2013-04-22 06:17:58
不是'set'做你想要做什么更好的方法,我意思是首先使用'set'。 – user2244984 2013-04-21 15:46:23
'std :: unique'是要走的路。看看函数的重载,你可以指定自己如何比较元素。 – 2013-04-21 15:47:28
矢量中的每个字段都是一个类。我不认为这套系统会起作用。 – KingJohnno 2013-04-21 15:47:30