I have a vector filled with some vertex object instances and need to sort it, according to its 'x' and after it its 'y' coordinate.
vertex.h
#ifndef VERTEX_H
#define VERTEX_H 1
class Vertex
{
private:
double __x;
double __y;
public:
Vertex(const double x, const double y);
bool operator<(const Vertex &b) const;
double x(void);
double y(void);
};
#endif // VERTEX_H
vertex.cpp
#include "vertex.h"
Vertex::Vertex(const double x, const double y) : __x(x), __y(y)
{
}
bool Vertex::operator<(const Vertex &b) const
{
return __x < b.x() || (__x == b.x() && __y < b.y());
}
double Vertex::x(void)
{
return __x;
}
double Vertex::y(void)
{
return __y;
}
run.cpp
#include <algorithm>
#include <stdio.h>
#include <vector>
#include "vertex.h"
void prnt(std::vector<Vertex *> list)
{
for(size_t i = 0; i < list.size(); i++)
printf("Vertex (x: %.2lf y: %.2lf)\n", list[i]->x(), list[i]->y());
}
int main(int argc, char **argv)
{
std::vector<Vertex *> list;
list.push_back(new Vertex(0, 0));
list.push_back(new Vertex(-3, 0.3));
list.push_back(new Vertex(-3, -0.1));
list.push_back(new Vertex(3.3, 0));
printf("Original:\n");
prnt(list);
printf("Sorted:\n");
std::sort(list.begin(), list.end());
prnt(list);
return 0;
}
What I expect as output is:
Original:
Vertex (x: 0.00 y: 0.00)
Vertex (x: -3.00 y: 0.30)
Vertex (x: -3.00 y: -0.10)
Vertex (x: 3.30 y: 0.00)
Sorted:
Vertex (x: -3.00 y: -0.10)
Vertex (x: -3.00 y: 0.30)
Vertex (x: 0.00 y: 0.00)
Vertex (x: 3.30 y: 0.00)
But what I actually get is:
Original:
Vertex (x: 0.00 y: 0.00)
Vertex (x: -3.00 y: 0.30)
Vertex (x: -3.00 y: -0.10)
Vertex (x: 3.30 y: 0.00)
Sorted:
Vertex (x: 0.00 y: 0.00)
Vertex (x: -3.00 y: -0.10)
Vertex (x: -3.00 y: 0.30)
Vertex (x: 3.30 y: 0.00)
I don't know what exactly is going wrong, any idea?