C++ 在向量中查找重复元素
我有一个向量,它包含元素的标识符以及x和Y坐标。我要做的是检查它们的x和y坐标是否相同如果他们确实删除了其中一个字段(基于另一个字段) 但是,我确实在谷歌上找到了关于“unique”功能的信息,因为所有的标识符都是唯一的,这不起作用吗?对吗 我在考虑使用嵌套的for循环来比较向量中的每个项,有更好的方法吗 谢谢 J您可以使用来丢弃重复项。但是,这不允许您对删除的元素执行任何操作。它们刚从容器里掉下来。当您需要这样做时,您可以使用以下方法: 与用于比较x坐标和y坐标的自定义比较函数一起使用。然后迭代向量一次,将每个元素与前一个元素进行比较 如果不想更改向量的顺序,也可以从头到尾迭代向量,并将每个元素与索引较高的所有元素进行比较:C++ 在向量中查找重复元素,c++,stl,C++,Stl,我有一个向量,它包含元素的标识符以及x和Y坐标。我要做的是检查它们的x和y坐标是否相同如果他们确实删除了其中一个字段(基于另一个字段) 但是,我确实在谷歌上找到了关于“unique”功能的信息,因为所有的标识符都是唯一的,这不起作用吗?对吗 我在考虑使用嵌套的for循环来比较向量中的每个项,有更好的方法吗 谢谢 J您可以使用来丢弃重复项。但是,这不允许您对删除的元素执行任何操作。它们刚从容器里掉下来。当您需要这样做时,您可以使用以下方法: 与用于比较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
}
}
}
for(int i=0;i
顺便说一句:根据您的具体要求,更好地处理二维空间中的对象的方法可能是自定义数据结构,如。我希望有帮助
#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"));
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
//样本坐标类
P类{
公众:
int x;
int-y;
P():x(0),y(0){}
P(inti,intj):x(i),y(j){}
};
//只是为了打印出来
std::ostream&operator不是set
做你想做的事的更好的方法,我的意思是首先使用set
。std::unique
是一种方法。查看函数的重载,您可以指定如何比较元素。向量中的每个字段都是一个类。“我不认为集合系统会起作用。”@KingJohnno每个字段都是一个类?你确定你的意思不是“对象”或是“类的实例”?@Philipp是的,对不起。这是漫长的一天!Hm这具有O(N^2)@hr_117的复杂性,通过命名的解决方案也是如此。你认为std::sort和std::unique是魔法吗?不,我不认为这会是魔法但是排序应该是O(N*logN)并且唯一,希望只有O(N)。