【发布时间】:2014-03-19 16:25:16
【问题描述】:
我是 C++ 新手,我正在尝试使用 C++ 计算 Point(x,y,z) 集的凸包。
我在main方法中调用了如下方法:
vector<Point> convexHull(Point Points[], int n) {
vector<Point> v;
// Find the bottommost Point
int ymin = Points[0].getY();
int min = 0;
for (int i = 1; i < n; i++) {
int y = Points[i].getY();
// Pick the bottom-most or chose the left most Point in case of tie
if ((y < ymin) || (ymin == y && Points[i].getX() < Points[min].getX()))
ymin = Points[i].getY(), min = i;
}
// Place the bottom-most Point at first position
Points[min] = Points[0].swap(Points[min]);
// Sort n-1 Points with respect to the first Point. A Point p1 comes
// before p2 in sorted ouput if p2 has larger polar angle (in
// counterclockwise direction) than p1
p0 = Points[0];
qsort(&Points[1], n - 1, sizeof (Point), compare);
// Create an empty stack and push first three Points to it.
stack<Point> S; // on debug the project I find that the problem is here
S.push(Points[0]);
S.push(Points[1]);
S.push(Points[2]);
// Process remaining n-3 Points
for (int i = 3; i < n; i++) {
// Keep removing top while the angle formed by Points next-to-top,
// top, and Points[i] makes a non-left turn
while (orientation(nextToTop(S), S.top(), Points[i]) != 2)
S.pop();
S.push(Points[i]);
}
// Now stack has the output Points, print contents of stack
while (!S.empty()) {
Point p = S.top();
cout << "(" << p.getX() << ", " << p.getY() << ", " << p.getZ() << ")" << endl;
v.push_back(Point(p.getX(), p.getY(), 0));
S.pop();
}
return v;
}
它给出了这个错误:
*** glibc detected *** /home/user/NetBeansProjects/DGILOG-ask/dist/Debug/GNU-Linux-x86/dgilog-task: malloc(): memory corruption (fast): 0x08de1238 ***
我在网上搜索过同样的错误,但我不知道该怎么办。
Point.cpp
#include <iostream>
#include <math.h>
#include <ostream>
using namespace std;
#include "Point.h"
Point::Point() : x(0), y(0), z(0) {
}
Point::Point(ostream &strm) {
strm << "Type the abscissa: ", cin >> this->x;
strm << "Type the ordinate: ", cin >> this->y;
strm << "Type the applicate: ", cin >> this->z;
}
Point::Point(float x, float y, float z) : x(x), y(y), z(z) {
}
/**
* Destructor
*/
Point::~Point() {
}
//Other methods
float Point::dist2D(Point &other) {
float xd = x - other.x;
float yd = y - other.y;
return sqrt(xd * xd + yd * yd);
}
float Point::dist3D(Point &other) {
float xd = x - other.x;
float yd = y - other.y;
float zd = z - other.z;
return sqrt(xd * xd + yd * yd + zd * zd);
}
Point Point::swap(Point p) {
Point aux(x, y, z);
x = p.x;
y = p.y;
z = p.z;
return aux;
}
void Point::print(ostream &strm) {
strm << "Point(" << this->x << "," << this->y << "," << this->z << ")" << endl;
}
bool Point::operator<(const Point &p) const {
return x < p.x || (x == p.x && y < p.y);
}
谢谢。
【问题讨论】:
-
您确定您的
Points[]至少有3 个元素吗?您是否使用调试器逐步完成了此操作? -
你应该做的是用
-g编译你的代码,然后通过valgrind运行它 -
1) 使用 qsort 退出。学习使用 std::sort。 2)你为什么使用vector
(好),同时使用Point数组(有问题)? -
在valgrind下运行程序(如果可以的话)
-
@clcto 是有超过 3 个元素。我试图用for循环显示他的内容。效果很好。