我有一组点坐标(x,y)存储在一个向量中。我想在向量中找到模式(最常见的点)。我发现很多算法如何计算模式,但是如何在点坐标数据集中找到模式?
typedef struct Points{
int x;
int y;
}Point
vector<Points> myPoint;
例如,myPoint: (0,0), (2,3), (6,2), (2,3), (4,1), ...模式为 (2,3),
Points currpoint = myPoint[0];
int counter = 1;
int maxcounter = 1;
Points mode = myPoint[0];
int n = myPoints.size();
for (int i = 1; i < n; ++i) {
if ( myPoint[i] == currpoint ) // !!! "==" produces error
++counter;
else { // next point started...
if (counter > maxcounter) { // new mode candidate
maxcounter = counter;
mode = currvalue;
}
currpoint = myPoint[i]; // ready to count next point
counter = 1;
}
}
cout << "Mode: " << mode << endl;
"=="操作数产生错误,我通过比较结构"点"来做正确的方法吗?
[已更正]
Points currpoint = myPoint[0];
int counter = 1;
int maxcounter = 1;
Points mode = myPoint[0];
int n = myPoints.size();
for (int i = 1; i < n; ++i) {
if ( myPoint[i].x == currpoint.x && myPoint[i].y == currpoint.y )
++counter;
else {
if (counter > maxcounter) {
maxcounter = counter;
mode = currvalue;
}
currpoint = myPoint[i];
counter = 1;
}
}
if (counter > maxcounter) {
maxcounter = counter;
mode = currvalue;
}
cout << "Mode: " << mode.x <<", "<< mode.y << endl;
您收到错误是因为==
没有被struct Points
重载。
两种解决方案:
-
struct Points
的过载==
操作员:typedef struct Points{ int x; int y; bool operator==(const Points& a) const { return (x == a.x && y == a.y); } }Point;
-
取代
if ( myPoint[i] == currpoint )
自
if ( myPoint[i].x==currpoint.x && myPoint[i].y==currpoint.y)