I'm new with c++ and I'm trying to calculate the convex hull of a Point(x,y,z) set using C++.
I have called the following method in the main method:
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;
}
It give this error:
*** glibc detected *** /home/user/NetBeansProjects/DGILOG-ask/dist/Debug/GNU-Linux-x86/dgilog-task: malloc(): memory corruption (fast): 0x08de1238 ***
I have searched in the web for the same error but I don't have understand what should I do.
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);
}
Thanks.
Points[]has at least 3 elements? Have you stepped through this with a debugger?-gand then run it through valgrind