I was using std::sort()
to sort a vector of points.
The point is a custom class, which indicates the value of the point and whether it's a beginning point of a segment.
I have implemented my own comparator for sorting. Rank by the value first, then put the beginning point before the ending point.
Here is my code:
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
class Point {
public:
Point(short value, bool isBegin)
: value(value), isBegin(isBegin) {}
short value;
bool isBegin;
};
class PointComparator {
public:
bool operator() (Point& a, Point& b) {
if (a.value != b.value) return a.value < b.value;
return a.isBegin;
}
};
short values[] = {
1070, 1145, 775, 860, 580, 655,
580, 655, -1105, -930, -1105, -930,
315, 400, 315, 400, -10, 185,
-10, 185, 340, 655, 340, 655,
-765, -615, -765, -615, 815, 1110,
815, 1110, -705, -175, -705, -175
};
int main(void) {
vector<Point> points;
for (int i = 0; i < 36; i ++) {
points.push_back(Point(values[i], (i & 1) == 0));
}
for (vector<Point>::size_type i = 0; i < points.size(); i ++) {
fprintf(stderr, "%d\t", points[i].value);
}
fprintf(stderr, "\n");
sort(points.begin(), points.end(), PointComparator());
for (vector<Point>::size_type i = 0; i < points.size(); i ++) {
fprintf(stderr, "%d\t", points[i].value);
}
fprintf(stderr, "\n");
return 0;
}
I built the program on my MacBook pro, using apple llvm 8.1.0 (clang-802.0.42), but the result is not what I expected.
I also tried it on my virtual machine, which using ubuntu operating system. The output is correct.
So, why? Is there a problem with my code?
Thanks.
Aucun commentaire:
Enregistrer un commentaire